home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / VideoToolbox 96.06.15 / VideoToolboxSources / GDVideo.c < prev    next >
Text File  |  1996-05-29  |  81KB  |  2,112 lines

  1. /* 
  2. GDVideo.c
  3. Copyright © 1989-1996 Denis G. Pelli
  4.  
  5. Complete set of routines to control video drivers directly, bypassing
  6. QuickDraw's Color and Palette Managers. There is a separate function call for
  7. each of the Control and Status Calls (csc) implemented by video drivers. They
  8. are described in Designing Cards and Drivers, 3rd Ed., chapter 9. A few new
  9. calls are documented in the Display Device Driver Guide Developer Note, which
  10. appeared on the January '94 Developer CD.
  11.  
  12. This file also contains several other helpful routines that deal with video
  13. device drivers. For background, read “Video synch”.
  14.  
  15. GDSetEntries
  16.  
  17. The most useful routine in this file is GDSetEntries. It implements a cscSetEntries Control 
  18. call to the video driver. This directly sets the video device's color lookup table (clut).
  19. (cscSetEntries is documented in Apple's books called
  20. Designing Cards and Drivers and Designing PCI Cards and Drivers.)
  21.  
  22. Apple also provides a high-level SetEntries() call, which is superficially similar, 
  23. but it gets interpreted by QuickDraw in complicated ways before ultimately 
  24. causing a cscSetEntries Control call to the video driver. 
  25. (SetEntries is documented in Inside Macintosh.) 
  26.  
  27. I always prefer GDSetEntries, because I want direct control over the clut.
  28.  
  29. THE MORE-USEFUL (HIGH-LEVEL) ROUTINES: (in alphabetical order)
  30.  
  31. char *GDCardName(GDHandle device);
  32. Returns the address of a C string containing the name of the video card. You
  33. should call DisposePtr() on the returned string when you no longer need it.
  34. Takes about 1.5 ms because Apple's slot routines are very slow. 
  35.  
  36. short GDClutSize(GDHandle device);
  37. Returns the number of entries in the video driver's clut in the current video
  38. mode (i.e. current pixel size). VideoToolbox.h defines a preprocessor macro
  39. GDCLUTSIZE(device) that expands to equivalent inline code.
  40.  
  41. long GDColors(GDHandle device)
  42. Number of colors, in the current mode.
  43.  
  44. short GDDacSize(GDHandle device)
  45. Figures out how many bits in the video dac.
  46.  
  47. OSErr GDSetDelay(GDHandle device,Boolean dontWaitForVBL,double nanoseconds);
  48. OSErr GDGetDelay(GDHandle device,Boolean *dontWaitForVBLPtr,double *nanosecondsPtr);
  49. These two routines support features, i.e. cscSetTimeDelays and cscGetTimeDelays, 
  50. unique to the built-in video driver of the
  51. PowerMac 7500 and 8500. Both routines will merely return innocuous errors (-17
  52. and -18) if used with any other video driver. Like most video drivers, the
  53. 7500/8500 video driver normally waits for VBL when loading the CLUT, but this can
  54. be overriden by the Boolean parameter dontWaitForVBL, in which case, from then on
  55. (until it's changed again or the machine is rebooted) the driver will load the
  56. CLUT immediately when it's called, without waiting for VBL. The second feature is
  57. that the video driver normally waits 800 ns after loading each RGB triplet to the
  58. CLUT, "to allow for the CLUT to settle and increment its address", and that time
  59. can be set by the parameter "nanoseconds". GDGetDelay() allows you to read the
  60. current setting of both parameters. GDSetDelay() allows you to set both
  61. parameters. If the supplied value of "nanoseconds" is infinite or NAN then it's
  62. ignored and only "dontWaitForVBL" is set. The 7500/8500 video driver was written
  63. by Apple Engineer Fernando Urbina, nano@apple.com. GDSetDelay() and GDSetDelay()
  64. were written by Denis Pelli, to allow convenient access to Fernando's custom
  65. control and status driver calls. Note that Fernando Urbina has also supplied a
  66. newer version of this driver (included in the VideoToolbox) that supports several
  67. extra resolutions, of which the most noteworthy is 640x480x120 Hz, which works
  68. well on the Apple 17" Multiscan.
  69.  
  70. Thus far, using visual inspection in TimeVideo, I've been unable to notice any
  71. bad effects of not waiting for VBL and reducing the waiting interval from 800 ns
  72. to zero. I asked Fernando Urbina, nano@apple.com, about it, since he put in the
  73. delays because he "does indeed get artifacts when updating the CLUT if we don't
  74. suppress interrupts while updating it." What were the artifacts? Fernando
  75. replies, "The delays are there because of hardware requirements:  When writing to
  76. the CLUT in a self-incrementing mode the hardware requires 800ns to update the
  77. address counter.  Of course, this is worst case.  ( We write the CLUT starting
  78. address and then the R, G, and B.  At the end of the B, the address counter for
  79. the CLUT will automatically increment to the next address.) I noticed some
  80. artifacts when doing palette animation -- one of the After Dark modules showed
  81. this very well."
  82.  
  83. OSErr GDGetDisplayMode(GDHandle device,unsigned long *displayModeIDPtr
  84.     ,unsigned short *modePtr,unsigned short *pagePtr,Ptr *baseAddrPtr);
  85. Calls cscGetCurMode, documented in Apple's new Display Device Driver Guide
  86. Developer Note on the January '94 Developer CD. The "display mode ID" is a new
  87. parameter, to support multi-resolution displays. Each display mode may have
  88. multiple pixel depths (which, confusingly, have also been called "modes"). This
  89. call will only be useful if the Display Manager is present (requires PowerPC or
  90. System 7.5) and if you're using the Display Manager, which is documented in a
  91. chapter in Inside Macintosh:Advanced Color Imaging, which thus far has appeared
  92. only in draft form on the December '94 Developer CD. The call returns an error
  93. if the video driver does not support the Display Manager. UNTESTED!!
  94.  
  95. OSErr GDGetEntries(GDHandle device,short start,short count,ColorSpec *table);
  96. Calls cscGetEntries. This is much as you'd expect after reading GDSetEntries
  97. below, EXCEPT that cscGetEntries writes into table[start],.... 
  98. whereas cscSetEntries reads from table[0],.... 
  99. Note that unless the gamma table is linear, the values returned may not
  100. be the same as those originally passed by GDSetEntries. So call
  101. GDUncorrectedGamma first. Try the demo TimeVideo.
  102.  
  103. OSErr GDGetGamma(GDHandle device,GammaTbl **myGammaTblHandle);
  104. Calls cscGetGamma. Returns a pointer to the Gamma table in the specified video
  105. device. (I.e. you pass it a pointer to your pointer, a handle, which it uses to
  106. load your pointer.)
  107.  
  108. OSErr GDGetPageCnt(GDHandle device,short mode,short *pagesPtr);
  109. Calls cscGetPageCnt. Called "GetPages" in Designing Cards and Drivers, 3rd Ed.
  110. You tell it which mode you're interested in. It tells you how many pages of
  111. video ram are available in that mode.
  112.  
  113. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr);
  114. Returns 0 if no such video mode, returns 1 if mode is available.
  115. If pixelSizePtr is not NULL, then sets *pixelSizePtr to pixelSize or -1 if unknown.
  116. If pagesPtr is not NULL, then sets *pagesPtr to pages.
  117.  
  118. unsigned char *GDName(GDHandle device);
  119. Returns a pointer to the name of the driver (a pascal string). This is quick.
  120. The string is part of the driver itself, so don't modify it or try to dispose of it.
  121.  
  122. unsigned char *GDNameStr(GDHandle device);
  123. Returns a pointer to the name of the driver, as a C string. 
  124. The string is static, and will be overwritten by the next call to GDNameStr().
  125.  
  126. ColorSpec *GDNewLinearColorTable(GDHandle device);
  127. Creates a default table for use when gdType==directType.
  128.  
  129. OSErr GDPrintGammaTable(FILE *o,GDHandle device);
  130.  
  131. OSErr GDRestoreDeviceClut(GDHandle device);
  132. Nominally equivalent to Apple's RestoreDeviceClut(), which is only available
  133. since System 6.05. However, I find that Apple's routine sometimes does nothing,
  134. whereas this routine always works. Passing a NULL argument causes restoration of
  135. cluts of all video devices.
  136.  
  137. OSErr GDSaveGamma(GDHandle device);
  138. OSErr GDRestoreGamma(GDHandle device);
  139. Use an internal cache to save and restore the device's gamma-correction table. 
  140. GDSaveGamma(NULL) and GDRestoreGamma(NULL) save and restore ALL devices.
  141. After the first request, GDSaveGamma() ignores subsequent requests to save the same 
  142. device's gamma table. GDRestoreGamma() no longer discards the saved copy (the cache), so multiple
  143. calls to GDRestoreGamma() will all be effective. You should call
  144. GDRestoreGamma before GDRestoreDeviceClut, because the video driver merely saves the gamma
  145. table when you do a cscSetGamma; the driver actually uses the gamma table to transform
  146. a new clut only when loading the clut.
  147.  
  148. OSErr GDSetEntries(GDHandle device,short start,short count,ColorSpec *table);
  149. Does a cscSetEntries call to the video card's driver, loading any
  150. number of clut entries with arbitrary rgb triplets. (Note that the driver will
  151. transform your rgb triplets via the gamma table before loading them into the
  152. clut; so call GDUncorrectedGamma first.) "device" specifies which video device's
  153. clut you want to load. "start" is either in the range 0 to clutSize-1,
  154. indicating which clut entry to load first (in "sequence mode"), or is -1
  155. (requesting "index mode"). "count" is the number of entries to be modified,
  156. minus 1. "table" is a ColorSpec array (not a ColorTable) containing the rgb
  157. triplets that you want to load into the clut. In sequence mode "start" must be
  158. in the range 0 to clutSize-1, the i-th element of table corresponds to the
  159. i-th entry in the clut, and the "value" field of each element of table is
  160. ignored. In index mode "start" must be -1, and the "value" field of each element
  161. of table indicates which clut entry to load it into. The arguments start, count,
  162. and (perhaps) table are the same as for the Color Manager call SetEntries(), documented in
  163. Inside Macintosh V-143. Note that cscSetEntries reads from table[0],.... 
  164. whereas cscGetEntries writes to table[start],.... 
  165. (Most drivers wait for blanking before modifying the
  166. clut. For a full discussion, read the VideoToolbox "Video synch" file.) You may
  167. also want to look at the file SetEntriesQuickly.c, which provides the
  168. functionality of GDSetEntries and GDDirectSetEntries, but bypasses the video
  169. driver to access the hardware directly.
  170.  
  171. OSErr GDSetEntriesByType(GDHandle device,short start,short count,ColorSpec *table);
  172. Checks the (**device).gdType field and calls cscSetEntries, cscDirectSetEntries,
  173. or nothing, as appropriate.
  174.  
  175. OSErr GDSetEntriesByTypeHighPriority(GDHandle device,short start,short count
  176.     ,ColorSpec *table);
  177. Calls GDSetEntriesByType() while the processor priority has been temporarily 
  178. raised to 7.
  179.  
  180. OSErr GDSetGamma(GDHandle device, GammaTbl *gamma);
  181. Calls cscSetGamma. Loads a Gamma table into the specified video device. The
  182. video driver will make a copy of your table. You can discard your table after
  183. making this call. Note that the video driver only uses the gamma table when
  184. performing cscSetEntries, i.e. when actually loading the clut. The structure of the
  185. gamma table is (finally!) documented in Designing Cards and Drivers, 3rd
  186. edition, pages 215-216. Beware of a discrepancy between the documentation and
  187. the definition in QuickDraw.h: gFormulaData is described as a byte array in the
  188. text, but is declared as a short array in the QuickDraw.h header file. NOTE: a
  189. few video drivers (Radius PowerView and SuperMac ColorCard) do not support gamma
  190. tables. The SuperMac ColorCard is well behaved, giving the appropriate error
  191. code, returned by GDSetGamma and GDGetGamma. The Radius PowerView reports no
  192. error yet ignores the GDSetGamma call and returns a table full of zeroes in
  193. response to GDGetGamma. See NOTE from Tom Busey below. However, if all you want
  194. to do is call GDUncorrectedGamma, then these limitations won't affect you,
  195. because the drivers that lack gamma tables always give you precisely the
  196. behaviour that one requests by calling GDUncorrectedGamma.
  197.  
  198. OSErr GDSetPageDrawn(GDHandle device,short page);
  199. Choose which page of video memory will be used by future drawing operations. 
  200. Untested.
  201.  
  202. OSErr GDSetPageShown(GDHandle device,short page);
  203. Choose which page of video memory we see. Untested.
  204.  
  205. OSErr GDUncorrectedGamma(GDHandle device);
  206. Asks GDSetGamma to load a linear gamma table, i.e. no correction. (The gamma
  207. correction implemented by table-lookup in the video driver is too crude for
  208. experiments that want accurate luminance control.)
  209.  
  210. int GDVersion(GDHandle device)
  211. Returns the version number of the driver. From the first word-aligned word after
  212. the name string. This is quick.
  213.  
  214. OSErr GDGetNextResolution()
  215. Implements cscGetNextResolution.
  216.  
  217. LESS-USEFUL (LOW LEVEL) ROUTINES:
  218.  
  219. OSErr GDControl(int refNum,int csCode,Ptr csParamPtr)
  220. Uses low-level PBControl() call to implement a "Control()" call that works! 
  221. I don't know why this wasn't discussed in Apple Tech Note 262.
  222.  
  223. OSErr GDDirectSetEntries(GDHandle device,short start,short count,ColorSpec *table);
  224. Calls cscDirectSetEntries. If your pixel depth is >8 then the cscSetEntries call is
  225. disabled, and you must use this instead of GDSetEntries().
  226.  
  227. VideoDriver *GDDriverAddress(GDHandle device);
  228. Returns a pointer to the driver, whether in ROM or RAM. Neither this prototype
  229. nor the definition of the VideoDriver structure are included in VideoToolbox.h.
  230.  
  231. OSErr GDGetDefaultMode(GDHandle device,short *modePtr)
  232. Calls cscGetDefaultMode. It tells you what the default mode is. I'm not sure
  233. what this means.
  234.  
  235. OSErr GDGetGray(GDHandle device,Boolean *flagPtr);
  236. Calls cscGetGray. Get gray flag. 0 for color. 1 if all colors mapped to
  237. luminance-equivalent gray tones.
  238.  
  239. OSErr GDGetInterrupt(GDHandle device,Boolean *flagPtr);
  240. Calls cscGetInterrupt. Get flag. 1 if VBL interrupts of this card are enabled. 0
  241. if disabled.
  242.  
  243. OSErr GDGetMode(GDHandle device,short *modePtr,short *pagePtr,Ptr *baseAddrPtr);
  244. Calls cscGetMode. It tells you the current mode, page of video memory, and the
  245. base address of that page.
  246.  
  247. OSErr GDGetPageBase(GDHandle device,short page,Ptr *baseAddrPtr);
  248. Calls cscGetPageBase. (Called "cscGetBaseAddr" in Designing Cards and Drivers, 3rd
  249. Ed.) You tell it which page of video memory you're interested in (in the current
  250. video mode). It tells you the base address of that page.
  251.  
  252. OSErr GDGrayPage(GDHandle device,short page);
  253. Calls cscGrayPage. (Called "cscGrayScreen" in Designing Cards and Drivers, 3rd
  254. Ed.) Fills the specified page with gray, i.e. the dithered desktop pattern. I'm
  255. not aware of any particular advantage in using this instead of FillRect().
  256. Designing Cards and Drivers, 3rd Edition, Chapter 9, says that for direct
  257. devices, i.e. >8 bit pixels, the driver will also load a linear,
  258. gamma-corrected, gray color table.
  259.  
  260. OSErr GDReset(GDHandle device, short *modePtr, short *pagePtr, Ptr *baseAddrPtr);
  261. Calls cscReset. Initialize the video card to its startup state, usually 1 bit
  262. per pixel. Returns the parameters of that state.
  263.  
  264. OSErr GDSetDefaultMode(GDHandle device,short mode);
  265. Calls cscSetDefault. Supposedly, you tell it what mode you want to start up with
  266. when you reboot. (I've never been able to get this to work. No error and no
  267. effect. Perhaps I've misunderstood its purpose.)
  268.  
  269. OSErr GDSetGray(GDHandle device,Boolean flag);
  270. Calls cscSetGray. Set gray flag. 0 for color. 1 if all colors mapped to
  271. luminance-equivalent gray tones.
  272.  
  273. OSErr GDSetInterrupt(GDHandle device,Boolean flag);
  274. Calls cscSetInterrupt. Set flag to 1 to enable VBL interrupts of this card, or 0
  275. to disable.
  276.  
  277. OSErr GDSetMode(GDHandle device,short mode,short page,Ptr *baseAddrPtr);
  278. Calls cscSetMode. You tell it what mode and video page you want. It sets 'em and
  279. returns the base address of that page in video memory. Also, because Apple said
  280. so, the video driver sets the entire clut to 50% gray. Note that this changes
  281. things behind QuickDraw's back. For most applications life will be simpler if
  282. you overtly ask QuickDraw to take charge by calling Apple's SetDepth() instead
  283. of GDSetMode(). WARNING: Apple now considers the mode numbers merely ordinal.
  284. E.g. on the 8•24 video card the 32-bit mode has mode number 0x84, not 0x85 as
  285. you might have expected on the basis of old Apple documentation and other Apple
  286. video cards.
  287.  
  288. OSErr GDSwitchMode(GDHandle device,short mode,long displayModeID,short page,Ptr *baseAddrPtr);
  289. Calls cscSwitchMode as documented in Designing PCI Video Cards and Drivers. PCI
  290. video drivers are required to support this call. It's like GDSetMode, but additionally
  291. allows you to specify the displayModeID, which determines the spatial resolution.
  292.  
  293. OSErr GDStatus(int refNum,int csCode,Ptr csParamPtr)
  294. Uses low-level PBStatus() call to implement a "Status()" call that works! The
  295. need for this is explained in Apple Tech Note 262, which was issued in response
  296. to my bug report in summer of '89.
  297.  
  298. PatchMacIIciVideoDriver();
  299. Fixes a crashing bug in the Mac IIci built-in video driver's implementation of
  300. cscGetEntries. The patch persists until reboot. It is unlikely that you will need
  301. to call this explicitly, PatchMacIIciVideoDriver() is automatically invoked the
  302. first time GDGetEntries is called. The Mac IIci built-in video driver
  303. (.Display_Video_Apple_RBV1 driver, version 0) has a bug that causes it to crash
  304. if you try to do a cscGetEntries Status request. PatchMacIIciVideoDriver() finds and
  305. patches the copy of the buggy driver residing in memory. (If the driver is
  306. ROM-based it first moves it to RAM, and then patches that.) Only two instructions
  307. are modified, to save & restore more registers. This fix persists only until the
  308. next reboot. If the patch is successfully applied the version number is increased
  309. by 100.
  310.  
  311. NOTES:
  312.  
  313. Several bugs in version 2 (in System ≤6.03) of the video driver for Apple's
  314. "Toby Frame Buffer" video card that affected use of the GetGamma call were
  315. fixed in version 3 (in System 6.04), apparently in response to my bug report to
  316. Apple.
  317.  
  318. The control/status-call parameter in a GDControl or GDStatus call specifies what
  319. you want done. See Designing Cards and Drivers, 3rd Edition, Chapter 9. (A few
  320. new calls are documented in the Display Device Driver Guide Developer Note.)
  321.  Note that sometime around 1990 Apple renamed some of the Control and Status
  322. calls, giving them names that better reflect their function. I followed suit.
  323. However, Apple neglected to update their book, Designing Cards and Drivers, now
  324. in its 3rd edition. Fortunately, they define both names in their Video.h header
  325. file. To avoid confusion, here are the equivalences. Note that "csc" stands for
  326. "Control and Status Call"
  327. Control call:
  328.  cscGrayPage =  cscGrayScreen = 5
  329. Status calls:
  330.  cscGetPageCnt = cscGetPages = 4
  331.  cscGetPageBase = cscGetBaseAddr = 5
  332.  
  333. Based on:
  334. Inside Macintosh-II (Device Manager)
  335. Designing Cards and Drivers, 3rd Edition, Chapter 9.
  336. Display Device Driver Guide Developer Note on the January '94 Developer CD.
  337. Tech Note 262: "Controlling Status Calls"
  338. "GreyScale Information" from AppleLink "Apple Technical Info"
  339. "Video Configuration ROM Software Specification" also from AppleLink,
  340. in "Developer Tech Support:Macintosh:32 Bit QuickDraw"
  341.  
  342. NOTES:
  343. Tom Busey (busey@indiana.edu) writes: "I'm using an 8-bit SuperMac ColorCard
  344. that a used computer dealer gave me when I ordered a Toby card. I discovered
  345. that the status and control calls for GDUncorrectedGamma return -17 and -18
  346. respectively, which means that the driver doesn't support different gammas.
  347. GDUncorrectedGamma returns an error message, but GDOpenWindow doesn't use the
  348. error message or pass it back to the calling program. I'm wondering if there are
  349. people using GDOpenWindow who think that they are getting a linear gamma but who
  350. are actually getting an error message and not learning about it."
  351.      Tom's facts are right, but he needn't worry. A few video drivers, e.g.
  352. Radius PowerView, and apparently the SuperMac ColorCard, don't implement gamma
  353. tables at all, but the error from GDUncorrectedGamma is probably not a concern.
  354. The real test is to run TimeVideo. TimeVideo does a write-and-read-back test of
  355. the clut of your video card. If that test passes then you can safely conclude
  356. that there's no gamma translation going on. So, as nearly every document in the
  357. VideoToolbox says: run TimeVideo and read the report.
  358.      Here's how gamma tables work. According to the Apple manual (Designing
  359. Cards and Drivers), the values in the rgb triplets that you supply in a
  360. cscSetEntries call to the video driver are first translated via the gamma table
  361. (each r,g, and b component separately) before being loaded into the CLUT
  362. hardware table. Most drivers maintain a gamma table internally (in computer
  363. memory) and allow you to get and set it via the cscGetGamma and cscSetGamma
  364. calls. A few video drivers (Radius PowerView, SuperMac ColorCard) don't support
  365. gamma tables. They load your rgb values directly into the CLUT, without
  366. translation. However, for users of the VideoToolbox that's usually fine, since
  367. that's exactly the behavior that we routinely request by calling
  368. GDUncorrectedGamma. Of course, if you want to load a custom gamma table, other
  369. than the identity transformation, then you'll be calling GDSetGamma, and you
  370. should make sure it does not return an error. (Alas, the Radius PowerView driver
  371. more or less ignores the cscSetGamma and cscGetGamma requests--GDGetGamma
  372. returns a table that's all zeroes--but the driver fails to report an error. I
  373. wrote to the Radius programmer a year ago, but they're no longer interested in
  374. working on that product.)
  375.     Patrick Flanagan (flanagan@deakin.edu.au) writes: "Can I be 100% sure, if I
  376. select "Special Gamma", in the Monitors Control Panel and choose "uncorrected
  377. gamma" for a video card, that this is the same as using GDUncorrectedGamma?"
  378. REPLY: That is what I would expect from reading all the relevant documentation.
  379. However, to be 100% certain of anything I would want to check it myself.
  380. TimeVideo calls GDUncorrectedGamma and then confirms that write-then-read tests
  381. of the CLUT return what was written. (Gamma-table translation is only done on
  382. the write, not undone on the read.) Thus TimeVideo will confirm for you that
  383. after calling GDUncorrectedGamma your video card has what Apple calls an
  384. "uncorrected" gamma table. However, TimeVideo does not check what you would get
  385. by merely selecting "uncorrected" gamma in the Monitors Control Panel. It would
  386. be reasonable to assume that you would get the same result since Monitors
  387. interacts with the video driver by the same Control and Status Calls as
  388. GDVideo.c does, so it must use the same cscSetGamma call as is used by
  389. GDUncorrectedGamma.
  390.  
  391. HISTORY:
  392. 9/29/89     dgp    added caution above that successive calls to cscSetEntries may be on one 
  393.                 frame.
  394. 11/21/89    dgp    corrected mode list: 0x80... as pointed out by Chuck Stein
  395. 11/30/89    dgp    added note above from Don Kelly.
  396.                 Added cautionary note above about GDSetEntries().
  397. 3/1/90        dgp    updated comments.
  398. 3/3/90        dgp    included Video.h instead of defining VDSetEntryRecord and VDPageInfo.
  399. 3/20/90        dgp    made compatible with MPW C.
  400. 3/23/90        dgp    changed char to unsigned char in VDDefModeRec
  401.                 and VDFlagRec to prevent undesirable sign extension.
  402. 4/2/90        dgp    Deleted mode argument from GDGrayScreen().
  403. 7/28/90        dgp Fixed stack overflow in GDGrayScreen, by declaring SysEnvRec static.
  404. 10/20/90    dgp    Apple has renamed the control and status calls, so I followed suit:
  405.                 •GDGetPageBase replaces GDGetBaseAddr
  406.                 •GDReset replaces GDInit
  407.                 •GDGrayPage replace GDGrayScreen
  408.                 •GDGetPageCnt replaces GDGetPages
  409. 2/12/91        dgp Discovered that the old bug in GDGrayPage is still present in System
  410.                 6.05, so I removed the conditional around the bug fix. TestGDVideo
  411.                 now works with: Mac II Video Card, Mac II Display Card (4•8), 
  412.                 Mac IIci Built-in Video, TrueVision NuVista, Mac IIsi Built-in Video.
  413. 7/22/91        dgp    Changed definition of csGTable from GammaTblPtr to Ptr, 
  414.                 to conform with MPW C.
  415. 8/24/91        dgp    Made compatible with THINK C 5.0.
  416. 10/22/91    dgp    With help from Bart Farell, converted all functions headers to
  417.                 Standard C style.
  418. 8/26/92        dgp    added a few miscellaneous comments
  419.                 In all routines, *baseAddrPtr is now set only if baseAddrPtr is not NULL.
  420. 10/10/92    dgp    Added GDRestoreDeviceClut(). Removed obsolete support for THINK C 4.
  421. 11/30/92    dgp corrected error in comment documenting values of argument to GDSetGray().
  422.                 Set flag to zero for color,1 for luminance-mapped gray.
  423. 12/9/92        dgp    Enhanced GDRestoreDeviceClut(). Passing a NULL argument now requests
  424.                 application to all devices. I only just learned that Apple's
  425.                 RestoreDeviceClut() behaves in this way.
  426. 12/15/92    dgp Renamed GDRestoreDeviceClut to GDRestoreDeviceClut to be consistent
  427.                 with Apple's capitalization of RestoreDeviceClut.
  428. 12/16/92    dgp Updated comments to be consistent with 3rd edition of Designing Cards
  429.                 and Drivers. •Renamed myGDHandle to "device", which is easier to read.
  430.                 Renamed GDLinearGamma to GDUncorrectedGamma, and generalized it
  431.                 to work with any size DAC. For compatibility with old programs
  432.                 VideoToolbox.h now has a #define statement making GDLinearGamma
  433.                 an alias for GDUncorrectedGamma.
  434. 12/30/92    dgp Updated some of the comments. Eliminated Files.h.
  435. 12/30/92    dgp Use GDClutSize() to determine clut size.
  436. 1/4/93        dgp In GDClutSize, check for fixedType.
  437. 1/5/93        dgp In GDClutSize, only set last clut entry.
  438.                 Added PatchMacIIciVideoDriver() to the end of this file, and 
  439.                 automatically invoke it the first time GDGetEntries is called.
  440. 1/6/93        dgp    Cleaned up GDClutSize. It now seems to work correctly in the direct modes.
  441. 1/18/93    dgp    Spruced up the documentation.
  442.             •Added all the code formerly in GDIdentify.c, but omitted the obsolete 
  443.             function GDIdentify(), which simply printed GDName() and GDVersion.
  444.             •Enhanced GDGetEntries() to avoid calling drivers that are known
  445.             to crash, returning a statusErr instead.
  446.             •Recoded PatchMacIIciVideoDriver() so as not to call GetScreenDevice.c.
  447. 2/1/93    dgp    Fixed endless loop in PatchMacIIciVideoDriver. Enhanced to deal with
  448.             ROM-based drivers as well.
  449. 2/5/93    dgp    Expanded the documentation of GDSetEntries above, and supplied sample
  450.             code showing how to load the clut.
  451. 2/7/93    dgp Fixed endless loop in PatchMacIIciVideoDriver.
  452. 2/20/93    dgp    Fixed bug in GDUncorrectedGamma() that was causing TestCluts to fail
  453.             for video devices that have nonstandard gamma tables. 
  454. 3/18/93    dgp    Fixed divide by zero error in GDClutSize.
  455. 4/6/93    dgp    GDGetPageCnt() now sets *pagePtr argument only if no error occurs.
  456.             Deleted GDModeName(). Removed assumption, in all routines, that there
  457.             is any particular correspondence between the video mode number and
  458.             the pixel size. Added two new routines, GDPixelSize and GDType,
  459.             that return the pixelSize and gdType (i.e. fixedType, clutType, or 
  460.             directType) of the device. Completely rewrote GDClutSize.
  461. 4/16/93    dgp    Streamlined GDClutSize() to make it fast enough for routine use.
  462. 4/19/93    dgp    Added GDNewLinearColorTable.
  463. 4/25/93    dgp    Made CntrlParam automatic instead of static.
  464. 4/25/93    dgp    Added GDColors(device) and GDPrintGammaTable(). Alphabetized the lists
  465.             of functions in the documentation above.
  466. 5/11/93    dgp    Changed GDPrintGammaTable() to accept a simple file pointer instead of
  467.             an array of two file pointers.
  468. 7/7/93    dgp enhanced GDDacSize() to return 8 unless the gamma table is present and
  469.             reasonable.
  470. 7/29/94    dgp    added GDNameStr().
  471. 9/5/94 dgp removed assumption in printf's that int==short.
  472. 10/25/94 dgp check for missing driver, (*device)->gdRefNum==0, and treat that case
  473.             just like  device==NULL. Devices created by NewGWorld have no driver.
  474. 12/29/94 dgp added GDGetDisplayMode(), calls cscGetCurMode, based on Apple's new
  475.             Display Device Driver Guide Developer Note on the January '94 Developer CD.
  476. 1/15/94 dgp GDPixelSize if supplied with a merely device record, with no associated 
  477.             device driver, then we just return (**(**device).gdPMap).pixelSize
  478. 3/22/95 dgp Added .Display_Video_Apple_DOMEMax to the list of drivers that don't
  479.             support cscGetEntries. Crash reported by Greg Jackson.
  480. 4/6/95 dgp Changed GDUncorrectedGamma() to pass a NULL gamma table pointer instead of
  481.             a linear gamma table, in the hopes that this might work even with the
  482.             few video drivers that don't fully support cscSetGamma.
  483. 4/21/95 dgp Fixed conditionals to cope with various versions of Video.h
  484. 6/8/95 dgp Made sure that the Mac structs are always 68k aligned.
  485. 6/26/95 dgp fixed error in dealing with UNIVERSAL_HEADERS==1 reported by Bart Farell.
  486.         We need the typedefs for DisplayModeID and DepthMode for universal headers
  487.         absent and also for version 1.
  488. 6/27/95 dgp Same for enum cscGetNextResolution.
  489. 6/30/95 dgp GDSaveGamma(NULL) and GDRestoreGamma(NULL) now save and restore ALL devices.
  490. 7/3/95 dgp After the first request, GDSaveGamma() ignores subsequent requests to save the same 
  491.         device's gamma table. GDRestoreGamma() no longer discards the saved copy, so multiple
  492.         calls to GDRestoreGamma() will all be effective. The effect of these changes is that
  493.         if you have multiple nested pairs of calls to GDSaveGamma and GDRestoreGamma, you will
  494.         end up with the desired result: every RestoreGamma will restore the screen to its
  495.         original gamma, same as it had at the time of the first call to GDSaveGamma.
  496. 8/10/95 bt & dgp. Bosco Tjan, tjan@cs.umn.edu, found that the conditionals needed to be 
  497.         adjusted to be compatible with Symantec C 8, because their Video.h is different from Apple's.
  498. 9/26/95 dgp. For compatibility with the ETO18 (CW7) universal headers, eliminated the now obsolete
  499.         typedefs of DepthMode (unsigned short) and DisplayModeID (unsigned long).
  500. 10/4/95 dgp Added code to GDCardName() to check for the presence of the Slot Manager, and
  501.         just return an empty string "" if it's not present. This will prevent crashes on PCI Macs.
  502. 10/4/95 dgp Added GDSwitchMode() which implements cscSwitchMode as documented in Designing PCI 
  503.         Video Cards and Drivers.
  504. 10/24/95 dgp Added GDGetDelay and GDSetDelay to implement the custom video driver calls
  505.         offered by the 7500/8500 video driver.
  506. 10/25/95 dgp After clarification from Fernando, fixed bug in GDGetDelays, so it should
  507.         now work reliably. I didn't know that I had to set the validMask bits.
  508. 12/4/95 dgp As requested by David Brainard, added #def of cscSwitchMode for backward compatibility
  509.         with older versions of THINK C.
  510. 3/4/96 dgp made compatible with THINK C 8, by replacing "SYMANTEC_C" by "SYMANTEC_C || THINK_C".
  511. 3/7/96 dgp Note that cscSetEntries reads from table[0],.... whereas cscGetEntries writes to table[start],.... 
  512. 5/1/96 dgp added GDDisposeGamma() to free the gamma tables.
  513. 5/28/96 dgp added test for UNIVERSAL_INTERFACES_VERSION<0x0212.
  514. */
  515.  
  516. #include "VideoToolbox.h"
  517. #include <ROMDefs.h>    // catDisplay,typeVideo,sRsrcName,sGammaDir
  518. //#include <Displays.h>
  519. void GetCPUProperties(char *cpuName,long *cpuHz,Boolean *hasL2Cache);
  520. void GetVideoProperties(GDHandle device,char *slotName,char *cardName,char *modelName);
  521. Boolean IsPCIMac(void);
  522.  
  523.  
  524. #if PRAGMA_ALIGN_SUPPORTED || __MWERKS__
  525.     #pragma options align=mac68k
  526. #endif
  527.  
  528. #if !UNIVERSAL_HEADERS
  529.     /* these declarations appear in Video.h, universal version 1 and later */
  530.     struct VDSwitchInfoRec{
  531.         unsigned short csMode;
  532.         unsigned long csData;
  533.         unsigned short csPage;
  534.         Ptr csBaseAddr;
  535.         unsigned long csReserved;
  536.     };
  537.     typedef struct VDSwitchInfoRec VDSwitchInfoRec;
  538.     enum{cscGetCurMode=10};
  539. #endif
  540. #if UNIVERSAL_HEADERS<2
  541.     enum{dRAMBasedMask=0x0040};    /* dCtlDriver is a handle (1) or pointer (0) */
  542.     typedef unsigned long UInt32;
  543. #endif
  544. #if UNIVERSAL_HEADERS<2 || SYMANTEC_C || THINK_C || __MWERKS__>=0x700
  545.     /* These declarations appeared in Apple's Video.h, universal version 2.0a3, */
  546.     /* and in "Universal Interfaces  DDK v23c5.  Monday, May 15, 1995"
  547.     /* but not in previous or subsequent versions (e.g. 2.1 aka ETO18),
  548.     /* until version 2.1.2 ETO 20, May 1996. */
  549.     // The version macro UNIVERSAL_INTERFACES_VERSION is defined in Apple's ConditionalMacros.h,
  550.     // but only since version 2.1 (which was distributed with CodeWarrior 8).
  551.     #if UNIVERSAL_INTERFACES_VERSION<0x0212
  552.         struct VDResolutionInfoRec {
  553.             unsigned long                    csPreviousDisplayModeID;    /* ID of the previous resolution in a chain */
  554.             unsigned long                    csDisplayModeID;            /* ID of the next resolution */
  555.             unsigned long                    csHorizontalPixels;            /* # of pixels in a horizontal line */
  556.             unsigned long                    csVerticalLines;            /* # of lines in a screen */
  557.             Fixed                            csRefreshRate;                /* Vertical Refresh Rate in Hz */
  558.             unsigned short                    csMaxDepthMode;                /* 0x80-based number representing max bit depth */
  559.             unsigned long                    csResolutionFlags;            /* flag bits */
  560.             unsigned long                    csReserved;                    /* Reserved */
  561.         };
  562.         typedef struct VDResolutionInfoRec VDResolutionInfoRec;
  563.         typedef VDResolutionInfoRec *VDResolutionInfoPtr;
  564.         #define cscGetNextResolution 17    /* this won't break even if cscSwitchMode has already been declared as an enum */
  565.         #define cscSwitchMode 10        /* this won't break even if cscSwitchMode has already been declared as an enum */
  566.     #endif
  567. #endif
  568.  
  569. typedef struct VDFlagRec {
  570.     unsigned char flag;
  571.     char pad;
  572. } VDFlagRec;
  573.  
  574. typedef struct VDDefModeRec{
  575.     unsigned char spID;
  576.     char pad;
  577. } VDDefModeRec;
  578.  
  579. typedef struct {
  580.     short flags;
  581.     short blanks[3];
  582.     short open;
  583.     short prime;
  584.     short control;
  585.     short status;
  586.     short close;
  587.     Str255 name;
  588. } VideoDriver;
  589. VideoDriver *GDDriverAddress(GDHandle device);
  590.  
  591. typedef struct {
  592.     short csCode;        // control code
  593.     short length;        // total parameter block bytes
  594.     char param[];        // control call data
  595. } ScrnCtl;
  596.  
  597. typedef struct {
  598.     short spDrvrHw;        // Slot Manager ID
  599.     short slot;            // Number of slot
  600.     long dCtlDevBase;    // Start of device's address space
  601.     short mode;            // screen characteristics
  602.     short flagMask;        // Which flag bits are used
  603.     short flags;        // device state: bit 0 = 0 = mono; bit 0 = 1 = color;
  604.                         // bit 11 =  1 = startup device; bit 15 = 1 = active
  605.     short colorTable;    // 'clut' id, default = -1
  606.     short gammaTable;    // Selects color intensity, default (MacII) = -1
  607.     Rect globalRect;    // global rectangle, main device topLeft = 0,0
  608.     short ctlCount;        // total control calls
  609.     ScrnCtl ctl;
  610. } Scrn;
  611.  
  612. typedef struct {
  613.     short scrnCount;    // Total devices
  614.     Scrn scrn;
  615. } Scrns;                // 'scrn' resource
  616.  
  617. #if PRAGMA_ALIGN_SUPPORTED || __MWERKS__
  618.     #pragma options align=reset
  619. #endif
  620.  
  621. Scrn **GDGetScrn(GDHandle device);
  622.  
  623. OSErr GDGetNextResolution(GDHandle device,unsigned long previousDisplayModeID
  624.     ,unsigned long *displayModeIDPtr,unsigned long *horizontalPixelsPtr
  625.     ,unsigned long *verticalLinesPtr,Fixed *refreshRatePtr
  626.     ,unsigned short *maxDepthModePtr);
  627.  
  628. OSErr GDGetDisplayMode(GDHandle device,unsigned long *displayModeIDPtr
  629.     ,unsigned short *modePtr,unsigned short *pagePtr,Ptr *baseAddrPtr)
  630. /*
  631. It tells you the current display mode, etc., but only if the video driver 
  632. supports the Display Manager.
  633. */
  634. {
  635.     VDSwitchInfoRec vdSwitchInfo;
  636.     int error;
  637.  
  638.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  639.     error=GDStatus((*device)->gdRefNum,cscGetCurMode,(Ptr) &vdSwitchInfo);
  640.     if(displayModeIDPtr!=NULL) *displayModeIDPtr=vdSwitchInfo.csData;
  641.     if(modePtr!=NULL) *modePtr=vdSwitchInfo.csMode;
  642.     if(pagePtr!=NULL) *pagePtr=vdSwitchInfo.csPage;
  643.     if(baseAddrPtr!=NULL) *baseAddrPtr=vdSwitchInfo.csBaseAddr;
  644.     return error;
  645. }
  646.  
  647. OSErr GDGetNextResolution(GDHandle device,unsigned long previousDisplayModeID
  648.     ,unsigned long *displayModeIDPtr,unsigned long *horizontalPixelsPtr
  649.     ,unsigned long *verticalLinesPtr,Fixed *refreshRatePtr
  650.     ,unsigned short *maxDepthModePtr)
  651. /*
  652. Tells you the next available displayModeID, after previousDisplayModeID.
  653. This is a new call, introduced for PCI video drivers.
  654. */
  655. {
  656.     VDResolutionInfoRec    vdSwitchInfo;
  657.     int error;
  658.  
  659.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  660.     vdSwitchInfo.csPreviousDisplayModeID=previousDisplayModeID;
  661.     error=GDStatus((*device)->gdRefNum,cscGetNextResolution,(Ptr) &vdSwitchInfo);
  662.     if(displayModeIDPtr!=NULL) *displayModeIDPtr=vdSwitchInfo.csDisplayModeID;
  663.     if(horizontalPixelsPtr!=NULL) *horizontalPixelsPtr=vdSwitchInfo.csHorizontalPixels;
  664.     if(verticalLinesPtr!=NULL) *verticalLinesPtr=vdSwitchInfo.csVerticalLines;
  665.     if(refreshRatePtr!=NULL) *refreshRatePtr=vdSwitchInfo.csRefreshRate;
  666.     if(maxDepthModePtr!=NULL) *maxDepthModePtr=vdSwitchInfo.csMaxDepthMode;
  667.     return error;
  668. }
  669.  
  670. OSErr GDSetPageDrawn(GDHandle device,short page)
  671. // Select a page of video memory to draw into.
  672. {
  673.     int error;
  674.     short flags;
  675.     Ptr baseAddr;
  676.     static long qD=-1;
  677.  
  678.     if(qD==-1)Gestalt(gestaltQuickdrawVersion,&qD);
  679.     error=GDGetPageBase(device,page,&baseAddr);
  680.     if(!error){
  681.         if(qD>=gestalt32BitQD){
  682.             flags=GetPixelsState((**device).gdPMap);
  683.             LockPixels((**device).gdPMap);
  684.         }
  685.         (**(**device).gdPMap).baseAddr=baseAddr;
  686.         if(qD>=gestalt32BitQD){
  687.             GDeviceChanged(device);
  688.             SetPixelsState((**device).gdPMap,flags);
  689.         }
  690.     }
  691.     return error;
  692. }
  693.  
  694. OSErr GDSetPageShown(GDHandle device,short page)
  695. // Select a page of video memory for display.
  696. {
  697.     int error;
  698.     short mode;
  699.  
  700.     error=GDGetMode(device,&mode,NULL,NULL);
  701.     if(error)return error;
  702.     return GDSetMode(device,mode,page,NULL);
  703. }
  704.  
  705. short GDType(GDHandle device)
  706. // Returns what would normally be in (**device).gdType, for occasions when
  707. // the GDevice record might be invalid because you called GDSetMode().
  708. {
  709.     int error;
  710.     static ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  711.  
  712.     error=GDSetEntries(device,0,0,&white);
  713.     if(!error)return clutType;
  714.     error=GDDirectSetEntries(device,0,0,&black);
  715.     if(!error)return directType;
  716.     return fixedType;
  717. }
  718.  
  719. short GDPixelSize(GDHandle device)
  720. // Returns what would normally be in (**(**device).gdPMap).pixelSize, for occasions
  721. // when the GDevice record might be invalid because you called GDSetMode().
  722. // Exception: if this is merely a device record, with no associated device driver,
  723. // then we just return (**(**device).gdPMap).pixelSize
  724. {
  725.     int error;
  726.     short mode;
  727.  
  728.     if((**device).gdRefNum==0)return (**(**device).gdPMap).pixelSize;
  729.     error=GDGetMode(device,&mode,NULL,NULL);
  730.     return GDModePixelSize(device,mode);
  731. }
  732.  
  733. short GDModePixelSize(GDHandle device,short mode)
  734. // Returns the pixelSize associated with a given video mode.
  735. // If you've changed the mode by calling GDSetMode and you're running a System 
  736. // older than 6.0.5 the answer may may be wrong for some of the newer video cards,
  737. // because they have ideosynchratic associations of video mode and pixel size.
  738. {
  739.     short j;
  740.     long version;
  741.  
  742.     if(mode==(**device).gdMode)return (**(**device).gdPMap).pixelSize;
  743.     Gestalt(gestaltSystemVersion,&version);
  744.     if(version>=0x605){            // Need new Palette Manager for reliable answer.
  745.         for(j=5;j>=0;j--)if(mode==HasDepth(device,1<<j,0,0))return 1<<j;
  746.     } else return 1<<(mode&7);    // Unreliable.
  747.     return 0;
  748. }
  749.  
  750. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr);
  751.  
  752. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr)
  753. // Returns 0 if no such mode, returns 1 if mode is available.
  754. // If pixelSizePtr is not NULL, then sets *pixelSizePtr to pixelSize or -1 if unknown.
  755. // If pagesPtr is not NULL, then sets *pagesPtr to pages.
  756. {
  757.     short pixelSize,i,hasDepthWorks,pages;
  758.     int error;
  759.     long system;
  760.     
  761.     Gestalt(gestaltSystemVersion,&system);
  762.     // On Mac IIci, Sys 6.07, HasDepth returns "mode" of 0x100 at all legal depths.
  763.     hasDepthWorks= system>=0x605     // New Palette Manager.
  764.         && HasDepth(device,(**(**device).gdPMap).pixelSize,0,0)==(**device).gdMode;
  765.     if(hasDepthWorks){
  766.         for(i=0;i<6;i++){
  767.             pixelSize=1<<i;
  768.             if(mode!=HasDepth(device,pixelSize,0,0))continue;
  769.             if(pixelSizePtr!=NULL)*pixelSizePtr=pixelSize;
  770.             if(pagesPtr!=NULL){
  771.                 error=GDGetPageCnt(device,mode,&pages);
  772.                 if(error)pages=1;
  773.                 *pagesPtr=pages;
  774.             }
  775.             return 1;
  776.         }
  777.         return 0;
  778.     }else{
  779.         // If HasDepth doesn't work properly then we can still find out whether the
  780.         // mode is available by asking the video driver for a page count, but
  781.         // I don't know of any discreet way to find out the pixelSize.
  782.         // Calling SetDepth would work, but that would irritate the user who has to
  783.         // watch and wait. 
  784.         error=GDGetPageCnt(device,mode,&pages);
  785.         if(error)pages=0;
  786.         if(pagesPtr!=NULL)*pagesPtr=pages;
  787.         if(mode==(**device).gdMode)pixelSize=(**(**device).gdPMap).pixelSize;
  788.         else pixelSize=-1;        // Unknown.
  789.         if(pixelSizePtr!=NULL)*pixelSizePtr=pixelSize;
  790.         return (pages>0);
  791.     }
  792. }
  793.  
  794. short gdClutSizeTable[33]={0,1<<1,1<<2,0,1<<4,0,0,0,1<<8,0,0,0,0,0,0,0,1<<5
  795. ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1<<8};
  796.  
  797. long GDColors(GDHandle device)
  798. // Returns the number of colors, in the current mode.
  799. {
  800.     long colors=0;
  801.     short pixelSize;
  802.     
  803.     if(device==NULL)return 2;    // for compatibility with 1-bit QuickDraw
  804.     pixelSize=(**(**device).gdPMap).pixelSize;
  805.     if(pixelSize>=1 && pixelSize<=8)colors=1<<pixelSize;
  806.     if(pixelSize==16)colors=1L<<15;
  807.     if(pixelSize==32)colors=1L<<24;
  808.     return colors;
  809. }
  810.  
  811. short GDClutSize(GDHandle device)
  812. // Returns the number of entries in the clut, in the current mode.
  813. {
  814.     short clutSize;
  815.     
  816.     // Method 1. Estimate clut size from pixel size.
  817.     clutSize=gdClutSizeTable[(**(**device).gdPMap).pixelSize];
  818.  
  819.     #if 0
  820.     // Method 2. Measure the clut's size by trying to load it.
  821.     if(GDType(device)==directType){
  822.         int error,i;
  823.         static const ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  824.         ColorSpec *table;
  825.         for(clutSize=256;clutSize>1;clutSize>>=1){
  826.             table=GDNewLinearColorTable(device);
  827.             if(table==NULL)PrintfExit("GDClutSize: out of memory.\n");
  828.             error=GDDirectSetEntries(device,0,clutSize-1,table);
  829.             DisposePtr((Ptr)table);
  830.             if(!error)break;
  831.         }
  832.     }
  833.     #endif
  834.     
  835.     return clutSize;
  836. }
  837.  
  838. short GDDacSize(GDHandle device)
  839. // Figures out how many bits in the video dac. Answers for each device are cached.
  840. {
  841.     short dacSize,i;
  842.     static short dacSizeCache[MAX_SCREENS];
  843.     static GDHandle deviceCache[MAX_SCREENS];
  844.     int error;
  845.     GammaTbl *gammaTblPtr=NULL;
  846.  
  847.     for(i=0;i<MAX_SCREENS;i++)if(device==deviceCache[i])return dacSizeCache[i];
  848.     error=GDGetGamma(device,&gammaTblPtr);        // Takes 200 µs.
  849.     if(error || gammaTblPtr==NULL || gammaTblPtr->gDataWidth==0)dacSize=8;                            // Oops. Take a guess.
  850.     else dacSize=gammaTblPtr->gDataWidth;
  851.     for(i=0;i<MAX_SCREENS;i++)if(NULL==deviceCache[i]){
  852.         deviceCache[i]=device;
  853.         dacSizeCache[i]=dacSize;
  854.         break;
  855.     }
  856.     return dacSize;
  857. }
  858.  
  859. ColorSpec *GDNewLinearColorTable(GDHandle device)
  860. // Creates a default table for use when gdType==directType.
  861. {
  862.     short clutSize,i;
  863.     ColorSpec *table,*linearTable;
  864.     
  865.     clutSize=GDClutSize(device);
  866.     table=linearTable=(ColorSpec *)NewPtr(clutSize*sizeof(linearTable[0]));
  867.     if(linearTable!=NULL)for(i=0;i<clutSize;i++){
  868.         table->rgb.red=table->rgb.green=table->rgb.blue
  869.             =(0xffffL*i+clutSize/2)/(clutSize-1);
  870.         table++;
  871.     }
  872.     return linearTable;
  873. }
  874.  
  875. /*
  876. Nominally equivalent to Apple's RestoreDeviceClut(), which is only available
  877. since System 6.05. However, I find that Apple's routine sometimes does nothing,
  878. whereas this routine always works. Passing a NULL argument causes restoration of
  879. cluts of all video devices.
  880. */
  881. OSErr GDRestoreDeviceClut(GDHandle device)
  882. {
  883.     int error,lastError;
  884.  
  885.     // If NULL, then call ourselves for each device.
  886.     if(device==NULL){
  887.         lastError=0;
  888.         device=GetDeviceList();
  889.         while(device!=NULL) {
  890.             if(TestDeviceAttribute(device,screenDevice) && TestDeviceAttribute(device,screenActive)){
  891.                 error=GDRestoreDeviceClut(device);
  892.                 if(error)lastError=error;
  893.             }
  894.             device=GetNextDevice(device);
  895.         }
  896.         return lastError;
  897.     }
  898.     if(GDType(device)!=directType){
  899.         error=GDSetEntries(device,0,(**(**(**device).gdPMap).pmTable).ctSize
  900.             ,((**(**(**device).gdPMap).pmTable)).ctTable);
  901.     }else error=GDSetGamma(device,NULL);
  902.     return error;
  903. }
  904.  
  905. GammaTbl **savedGammaTable[MAX_SCREENS];
  906.  
  907. OSErr GDDisposeGamma(GDHandle device)
  908. {
  909.     int error=0,lastError,i;
  910.  
  911.     // If NULL, then call ourselves for each device.
  912.     if(device==NULL){
  913.         lastError=0;
  914.         device=GetDeviceList();
  915.         while(device!=NULL) {
  916.             if(TestDeviceAttribute(device,screenDevice) && TestDeviceAttribute(device,screenActive)){
  917.                 error=GDDisposeGamma(device);
  918.                 if(error)lastError=error;
  919.             }
  920.             device=GetNextDevice(device);
  921.         }
  922.         return lastError;
  923.     }
  924.     if(device==NULL || (*device)->gdType==fixedType)return 0;
  925.     i=GetScreenIndex(device);
  926.     if(i>=MAX_SCREENS)return 1;
  927.     if(savedGammaTable[i]==NULL)return 0;
  928.     DisposeHandle((Handle)savedGammaTable[i]);
  929.     savedGammaTable[i]=NULL;
  930.     return error;
  931. }
  932.  
  933. OSErr GDSaveGamma(GDHandle device)
  934. {
  935.     GammaTbl *gamma;
  936.     int error,lastError;
  937.     long size;
  938.     int i;
  939.  
  940.     // If NULL, then call ourselves for each device.
  941.     if(device==NULL){
  942.         lastError=0;
  943.         device=GetDeviceList();
  944.         while(device!=NULL) {
  945.             if(TestDeviceAttribute(device,screenDevice) && TestDeviceAttribute(device,screenActive)){
  946.                 error=GDSaveGamma(device);
  947.                 if(error)lastError=error;
  948.             }
  949.             device=GetNextDevice(device);
  950.         }
  951.         return lastError;
  952.     }
  953.     if(device==NULL || (*device)->gdType==fixedType)return 0;
  954.     i=GetScreenIndex(device);
  955.     if(i>=MAX_SCREENS)return 1;
  956.     if(savedGammaTable[i]!=NULL)return 0;
  957.      error=GDGetGamma(device,&gamma);
  958.     if(error)return error;
  959.     size=gamma->gChanCnt*gamma->gDataCnt;
  960.     if(gamma->gDataWidth>8)size*=2;
  961.     size+=sizeof(GammaTbl)+gamma->gFormulaSize;
  962.     error=PtrToHand(gamma,(Handle *)&savedGammaTable[i],size);
  963.     return error;
  964. }
  965.  
  966. OSErr GDRestoreGamma(GDHandle device)
  967. {
  968.     int i,error,lastError;
  969.     
  970.     // If NULL, then call ourselves for each device.
  971.     if(device==NULL){
  972.         lastError=0;
  973.         device=GetDeviceList();
  974.         while(device!=NULL) {
  975.             if(TestDeviceAttribute(device,screenDevice) && TestDeviceAttribute(device,screenActive)){
  976.                 error=GDRestoreGamma(device);
  977.                 if(error)lastError=error;
  978.             }
  979.             device=GetNextDevice(device);
  980.         }
  981.         return lastError;
  982.     }
  983.     if((*device)->gdType==fixedType)return 0;
  984.     i=GetScreenIndex(device);
  985.     if(i>=MAX_SCREENS || savedGammaTable[i]==NULL)return 1;
  986.     error=GDSetGamma(device,*savedGammaTable[i]);
  987.     if(error)return error;
  988.     if(0){
  989.         DisposeHandle((Handle)savedGammaTable[i]);
  990.         savedGammaTable[i]=NULL;
  991.     }
  992.     return 0;
  993. }    
  994.  
  995. OSErr GDGetDefaultGamma(GDHandle device,GammaTbl **gammaTbl)
  996. // Looks for a default gamma table in both places that Apple says to look,
  997. // but usually comes up empty handed.
  998. {
  999.     int error,i,slot;
  1000.     Scrn **scrn;
  1001.     GammaTbl **gammaHandle,*gamma;
  1002.     SpBlock spBlock;
  1003.     Ptr ptr;
  1004.  
  1005.     gammaHandle=NULL;
  1006.     if(CountResources('gama')>0){// Any 'gama' resources available in System file?
  1007.         // Check to see if 'scrn' resource in System file specifies a 'gama' resource.
  1008.         scrn=GDGetScrn(device);
  1009.         if(scrn!=NULL && (**scrn).gammaTable!=-1)
  1010.             gammaHandle=(GammaTbl **)GetResource('gama',(**scrn).gammaTable);
  1011.         DisposeHandle((Handle)scrn);
  1012.     }
  1013.     if(gammaHandle!=NULL){
  1014.         // Got gamma table from 'gama' resource.
  1015.         gamma=(GammaTbl *)NewPtr(GetHandleSize((Handle)gammaHandle));
  1016.         if(gamma==NULL)return MemError();
  1017.         BlockMove(*gammaHandle,gamma,GetHandleSize((Handle)gammaHandle));
  1018.         DisposeHandle((Handle)gammaHandle);
  1019.     }else{
  1020.         // Try to get this device's default gamma table from Slot Manager.
  1021.         spBlock.spSlot=slot=GetDeviceSlot(device);
  1022.         spBlock.spID=0;
  1023.         spBlock.spExtDev=0;
  1024.         spBlock.spTBMask=3;            // match only spCategory and spCType
  1025.         spBlock.spCategory=catDisplay;
  1026.         spBlock.spCType=typeVideo;    // this might be too restrictive, excludes LCD
  1027.         do{
  1028.             error=SNextTypeSRsrc(&spBlock);
  1029.             if(error)return error;
  1030.         }while(spBlock.spSlot!=slot || spBlock.spRefNum!=(**device).gdRefNum);
  1031.         
  1032.         if(0){
  1033.             // Print sResource name
  1034.             spBlock.spID=sRsrcName;
  1035.             error=SGetCString(&spBlock);
  1036.             printf("Slot resource \"%s\"\n",spBlock.spResult);
  1037.             if(error)return error;
  1038.             DisposePtr((Ptr)spBlock.spResult);
  1039.         }
  1040.         
  1041.         // Look for gamma directory. Unfortunately many video devices don't have one.
  1042.         spBlock.spID=sGammaDir;
  1043.         error=SFindStruct(&spBlock);
  1044.         if(error)return error;
  1045.         
  1046.         // Retrieve default gamma table
  1047.         spBlock.spID=0x80;
  1048.         error=SGetBlock(&spBlock);
  1049.         if(error)return error;
  1050.         gamma=(GammaTbl *)spBlock.spResult;
  1051.         ptr=(Ptr)spBlock.spResult+6;
  1052.         if(0)printf("Gamma table \"%s\", %ld bytes\n",ptr,GetPtrSize((Ptr)gamma));
  1053.         ptr+=strlen(ptr)+1;                // table is just past string
  1054.         ptr=(Ptr)((long)(ptr+1)&~1L);    // round up to even address
  1055.         i=ptr-(Ptr)gamma;
  1056.         BlockMove(ptr,(Ptr)gamma,GetPtrSize((Ptr)gamma)-i);
  1057.         SetPtrSize((Ptr)gamma,GetPtrSize((Ptr)gamma)-i);
  1058.     }
  1059.     *gammaTbl=gamma;
  1060.     return 0;
  1061. }
  1062.  
  1063. Scrn **GDGetScrn(GDHandle device)
  1064. // Returns handle to a copy of the specific scrn resource for this device,
  1065. // or NULL if none.
  1066. {
  1067.     int error=0,i,j;
  1068.     Scrns **scrns;
  1069.     Scrn *scrn,**scrnHandle;
  1070.     ScrnCtl *ctl;
  1071.     int scrnCount;
  1072.     long size;
  1073.  
  1074.     scrns=(Scrns **)GetResource('scrn',0);
  1075.     if(ResError())return NULL;
  1076.     HLockHi((Handle)scrns);
  1077.     scrnCount=(**scrns).scrnCount;
  1078.     scrn=&(**scrns).scrn;
  1079.     for(i=0;i<scrnCount;i++){
  1080.         if(0 && scrn->slot==GetDeviceSlot(device)){
  1081.             printf("Slot %d,",(int)scrn->slot);
  1082.             printf("mode %d,",(int)scrn->mode);
  1083.             printf("colorTable %d,",(int)scrn->colorTable);
  1084.             printf("gammaTable %d,",(int)scrn->gammaTable);
  1085.             printf("%d control calls:",(int)scrn->ctlCount);
  1086.         }
  1087.         ctl=&scrn->ctl;
  1088.         for(j=0;j<scrn->ctlCount;j++){
  1089.             if(0 && scrn->slot==GetDeviceSlot(device))printf(" %d",(int)ctl->csCode);
  1090.             ctl=(ScrnCtl *)((long)(ctl+1)+ctl->length);
  1091.         }
  1092.         if(0 && scrn->slot==GetDeviceSlot(device))printf("\n");
  1093.         size=(long)ctl-(long)scrn;
  1094.         if(scrn->slot==GetDeviceSlot(device))break;
  1095.         scrn=(Scrn *)ctl;
  1096.     }
  1097.     if(i<scrnCount){
  1098.         if(error)return NULL;
  1099.         scrnHandle=(Scrn **)NewHandle(size);
  1100.         BlockMove(scrn,*scrnHandle,size);
  1101.     }else scrnHandle=NULL;
  1102.     ReleaseResource((Handle)scrns);
  1103.     return scrnHandle;
  1104. }
  1105.  
  1106. OSErr GDUncorrectedGamma(GDHandle device)
  1107. /*
  1108. Loads a linear gamma table into the specified video device, to defeat the
  1109. driver's attempt to do gamma correction.
  1110.  
  1111. According to Designing Cards and Drivers, 3rd edition, passing a NULL
  1112. GammaTblPtr instructs the driver to create a linear table. 
  1113.  
  1114. */
  1115. {
  1116.     int error,i;
  1117.     GammaTbl *gamma=NULL;
  1118.     char *gData;
  1119.  
  1120.     if(0){
  1121.         /*
  1122.         The the following code first examines the current
  1123.         gamma table, and, if it's a plain vanilla table, as described in Designing Cards
  1124.         and Drivers, then we write-in the desired linear table. If it's fancy (or if the
  1125.         driver doesn't support GDGetGamma) then we pass a NULL pointer, letting the driver
  1126.         create the new table. Hopefully this will work with all drivers.
  1127.         */
  1128.         error=GDGetGamma(device,&gamma);
  1129.         if(!error && gamma->gVersion==0 && gamma->gChanCnt==1 && gamma->gDataWidth<=8){
  1130.             // Overwrite the standard table
  1131.             gData = (char *)&gamma->gFormulaData+gamma->gFormulaSize;
  1132.             for(i=0;i<gamma->gDataCnt;i++)gData[i]=i;
  1133.         }else{
  1134.             // A fancy table implies a new driver, so let it do the work.
  1135.             gamma=NULL;
  1136.         }
  1137.     }
  1138.     error=GDSetGamma(device,gamma);
  1139.     return error;
  1140. }
  1141.  
  1142. /* KillIO doesn't do anything, so I didn't bother to implement it. */
  1143.  
  1144. OSErr GDPrintGammaTable(FILE *o,GDHandle device)
  1145. {
  1146.     unsigned char *byte;
  1147.     unsigned short *word;
  1148.     int error,i,j,identity;
  1149.     GammaTbl *gamma;
  1150.     
  1151.     if((**device).gdType==fixedType)return statusErr;
  1152.     error=GDGetGamma(device,&gamma);
  1153.     if(error){
  1154.         fprintf(o,"GetGamma: GDGetGamma() error %d\n",error);
  1155.         if(error==statusErr)
  1156.             fprintf(o,"The video driver doesn't support this call.\n");
  1157.         return error;
  1158.     }
  1159.     byte=(unsigned char *)gamma->gFormulaData+gamma->gFormulaSize;
  1160.     word=(unsigned short *)byte;
  1161.     identity=1;
  1162.     if(gamma->gDataWidth<=8)
  1163.         for(i=0;i<gamma->gDataCnt;i++)identity &= (i==byte[i]);
  1164.     else
  1165.         for(i=0;i<gamma->gDataCnt;i++)identity &= (i==word[i]);
  1166.     if(identity){
  1167.         fprintf(o,"Gamma Table: identity transformation\n");
  1168.     }else{
  1169.         fprintf(o,"Gamma Table:\n");
  1170.         fprintf(o,"at 0x%lx,gDataWidth %d,gDataCnt %d,gVersion %d,gType %d,gFormulaSize %d,gChanCnt %d\n"
  1171.             ,gamma,(int)gamma->gDataWidth,(int)gamma->gDataCnt,(int)gamma->gVersion
  1172.             ,(int)gamma->gType,(int)gamma->gFormulaSize,(int)gamma->gChanCnt);
  1173.         for(i=0;i<gamma->gDataCnt;i+=64) {
  1174.             fprintf(o,"%3d: ",i);
  1175.             if(gamma->gDataWidth<=8)
  1176.                 for(j=0;j<16;j++) fprintf(o," %3u",byte[i+j]);
  1177.             else
  1178.                 for(j=0;j<16;j++) fprintf(o," %3u",word[i+j]);
  1179.             fprintf(o,"\n");
  1180.         }
  1181.     }
  1182.     return 0;
  1183. }
  1184.  
  1185. OSErr GDReset(GDHandle device, short *modePtr, short *pagePtr, Ptr *baseAddrPtr)
  1186. /*
  1187. Initialize the video card to its startup state, usually 1 bit per pixel. Returns
  1188. the parameters of that state.
  1189. */
  1190. {
  1191.     VDPageInfo myVDPageInfo;
  1192.     int error;
  1193.  
  1194.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1195.     myVDPageInfo.csMode= *modePtr;
  1196.     myVDPageInfo.csPage= *pagePtr;
  1197.     error=GDControl((*device)->gdRefNum,cscReset,(Ptr) &myVDPageInfo);
  1198.     *modePtr=myVDPageInfo.csMode;
  1199.     *pagePtr=myVDPageInfo.csPage;
  1200.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1201.     return error;
  1202. }
  1203.  
  1204. OSErr GDSetMode(GDHandle device,short mode,short page,Ptr *baseAddrPtr)
  1205. {
  1206.     VDPageInfo myVDPageInfo;
  1207.     int error;
  1208.  
  1209.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1210.     myVDPageInfo.csMode=mode;
  1211.     myVDPageInfo.csPage=page;
  1212.     error=GDControl((*device)->gdRefNum,cscSetMode,(Ptr) &myVDPageInfo);
  1213.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1214.     return error;
  1215. }
  1216.  
  1217. OSErr GDSwitchMode(GDHandle device,short mode,long displayModeID,short page,Ptr *baseAddrPtr);
  1218.  
  1219. OSErr GDSwitchMode(GDHandle device,short mode,long displayModeID,short page,Ptr *baseAddrPtr)
  1220. /* cscSwitchMode is documented in Designing PCI Video Cards and Drivers. */
  1221. {
  1222.     VDSwitchInfoRec vdSwitchInfo;
  1223.     int error;
  1224.  
  1225.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1226.     vdSwitchInfo.csMode=mode;
  1227.     vdSwitchInfo.csData=displayModeID;
  1228.     vdSwitchInfo.csPage=page;
  1229.     error=GDControl((*device)->gdRefNum,cscSwitchMode,(Ptr) &vdSwitchInfo);
  1230.     if(baseAddrPtr!=NULL) *baseAddrPtr=vdSwitchInfo.csBaseAddr;
  1231.     return error;
  1232. }
  1233.  
  1234. OSErr GDSetEntriesByType(GDHandle device,short start,short count,ColorSpec *table)
  1235. // Calls GDSetEntries or GDDirectSetEntries or nothing, as appropriate.
  1236. // Assumes that the GDevice record is valid, i.e. that the user has not
  1237. // called GDSetMode.
  1238. {
  1239.     switch((*device)->gdType){
  1240.     case fixedType:
  1241.         return statusErr;
  1242.     case clutType:
  1243.         return GDSetEntries(device,start,count,table);
  1244.     case directType:
  1245.         return GDDirectSetEntries(device,start,count,table);
  1246.     }
  1247.     return 1;
  1248. }
  1249.  
  1250. OSErr GDSetEntriesByTypeHighPriority(GDHandle device,short start,short count
  1251.     ,ColorSpec *table)
  1252. {
  1253.     char priority;
  1254.     int error;
  1255.  
  1256.     priority=7;
  1257.     SwapPriority(&priority);
  1258.     error=GDSetEntriesByType(device,start,count,table);
  1259.     SwapPriority(&priority);
  1260.     return error;
  1261. }
  1262.  
  1263. OSErr GDSetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1264. // Note that cscSetEntries reads from table[0],.... whereas cscGetEntries writes to table[start],.... 
  1265. {
  1266.     VDSetEntryRecord vDSetEntryRecord;
  1267.     int error;
  1268.  
  1269.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1270.     vDSetEntryRecord.csStart=start;
  1271.     vDSetEntryRecord.csCount=count;
  1272.     vDSetEntryRecord.csTable=table;
  1273.     error=GDControl((*device)->gdRefNum,cscSetEntries,(Ptr) &vDSetEntryRecord);
  1274.     return error;
  1275. }
  1276.  
  1277. OSErr GDSetGamma(GDHandle device, GammaTbl *gamma)
  1278. {
  1279.     int error;
  1280.     VDGammaRecord myVDGammaRecord;
  1281.  
  1282.     myVDGammaRecord.csGTable=(Ptr)gamma;
  1283.     error=GDControl((*device)->gdRefNum,cscSetGamma,(Ptr) &myVDGammaRecord);
  1284.     return error;
  1285. }
  1286.  
  1287. OSErr GDGrayPage(GDHandle device,short page)
  1288. /*
  1289. Called "GrayScreen" in Designing Cards and Drivers, 3rd Ed. Fills the specified
  1290. page with gray, i.e. the dithered desktop pattern. I'm not aware of any
  1291. particular advantage in using this instead of FillRect().
  1292.  
  1293. Designing Cards and Drivers, 3rd Edition, Chapter 9, says that for direct
  1294. devices, i.e. >8 bit pixels, the driver will also load a linear,
  1295. gamma-corrected, gray color table.
  1296.  
  1297. Contrary to the documentation, version 2 (in System 6.03) of the video driver
  1298. for Apple's old video card requires that one supply the current mode as well.
  1299. Supplying a garbage mode screwed up the screen and soon hung the software. So
  1300. this code first obtains the current mode, and then supplies it in the GrayPage
  1301. Control call.
  1302. */
  1303. {
  1304.     VDPageInfo myVDPageInfo;
  1305.     int error;
  1306.     /* The rest of the arguments are used soley for the bug fix */
  1307.     short mode=0;        /* should be ignored, but isn't */
  1308.     short actualPage;    /* ignored */
  1309.     Ptr baseAddr;        /* ignored */
  1310.  
  1311.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1312.     
  1313.     /* Work around driver bug: get the mode */
  1314.     error=GDGetMode(device,&mode,&actualPage,&baseAddr);
  1315.     if(error)return error;
  1316.     myVDPageInfo.csMode=mode;
  1317.     
  1318.     myVDPageInfo.csPage=page;
  1319.     error=GDControl((*device)->gdRefNum,cscGrayPage,(Ptr) &myVDPageInfo);
  1320.     return error;
  1321. }
  1322.  
  1323. OSErr GDSetGray(GDHandle device,Boolean flag)
  1324. /*
  1325. Tells the driver whether you want colors (flag==0), or prefer that all colors be 
  1326. mapped to luminance-equivalent gray tones? (flag==1).
  1327. */
  1328. {
  1329.     VDFlagRec myVDFlagRec;
  1330.     int error;
  1331.  
  1332.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1333.     myVDFlagRec.flag=flag;
  1334.     error=GDControl((*device)->gdRefNum,cscSetGray,(Ptr) &myVDFlagRec);
  1335.     return error;
  1336. }
  1337.  
  1338. OSErr GDSetInterrupt(GDHandle device,Boolean flag)
  1339. /*
  1340. Set flag to 1 to enable VBL interrupts of this card, or 0 to disable. 
  1341. I don't know when it's appropriate to call this.
  1342. */
  1343. {
  1344.     VDFlagRec myVDFlagRec;
  1345.     int error;
  1346.  
  1347.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1348.     myVDFlagRec.flag=flag;
  1349.     error=GDControl((*device)->gdRefNum,cscSetInterrupt,(Ptr) &myVDFlagRec);
  1350.     return error;
  1351. }
  1352.  
  1353. OSErr GDDirectSetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1354. /*
  1355. If your pixel depth is >8 then the cscSetEntries Control call is disabled, and you use
  1356. cscDirectSetEntries instead. Except for that, GDDirectSetEntries is identical to GDSetEntries.
  1357. */
  1358. {
  1359.     VDSetEntryRecord vDSetEntryRecord;
  1360.     int error;
  1361.  
  1362.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1363.     vDSetEntryRecord.csStart=start;
  1364.     vDSetEntryRecord.csCount=count;
  1365.     vDSetEntryRecord.csTable=table;
  1366.     error=GDControl((*device)->gdRefNum,cscDirectSetEntries,(Ptr) &vDSetEntryRecord);
  1367.     return error;
  1368. }
  1369.  
  1370. OSErr GDSetDefaultMode(GDHandle device,short mode)
  1371. /*
  1372. Supposedly, you tell it what mode you want to start up with when you reboot.
  1373. (I've never been able to get this to work. No error and no effect. Perhaps I've
  1374. misunderstood its purpose.)
  1375. */
  1376. {
  1377.     VDDefModeRec myVDDefModeRec;
  1378.     int error;
  1379.  
  1380.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1381.     myVDDefModeRec.spID=mode;
  1382.     error=GDControl((*device)->gdRefNum,cscSetDefaultMode,(Ptr) &myVDDefModeRec);
  1383.     return error;
  1384. }
  1385.  
  1386. OSErr GDGetMode(GDHandle device,short *modePtr,short *pagePtr,Ptr *baseAddrPtr)
  1387. /*
  1388. It tells you the current mode, page of video memory, and the base address of that
  1389. page.
  1390. */
  1391. {
  1392.     VDPageInfo myVDPageInfo;
  1393.     int error;
  1394.  
  1395.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1396.     error=GDStatus((*device)->gdRefNum,cscGetMode,(Ptr) &myVDPageInfo);
  1397.     if(modePtr!=NULL)*modePtr=myVDPageInfo.csMode;
  1398.     if(pagePtr!=NULL)*pagePtr=myVDPageInfo.csPage;
  1399.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1400.     return error;
  1401. }
  1402.  
  1403. OSErr GDGetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1404. // Note that cscSetEntries reads from table[0],.... whereas cscGetEntries writes to table[start],.... 
  1405. /*
  1406. This is much as you'd expect after reading GDSetEntries above. Note that unless
  1407. the gamma table is linear, the values returned may not be the same as those
  1408. originally passed by GDSetEntries. So call GDUncorrectedGamma first. Note that
  1409. version 2 (in System 6.03) of the video driver for Apple's old video card had a
  1410. bug and did not support "indexed" mode, i.e. start==-1. This is fixed in System
  1411. 6.05. Apple's .Display_Video_Apple_RBV1 v. 0 video driver (built-in to Mac IIci)
  1412. crashes if you attempt to make this call. However, that's a thing of the past,
  1413. because we now first patch the driver to fix the bug. Try the demo TimeVideo.
  1414. */
  1415. {
  1416.     VDSetEntryRecord vDSetEntryRecord;
  1417.     int error;
  1418.     static Boolean bugsPatched=0;
  1419.     unsigned char *name;
  1420.     int version;
  1421.  
  1422.     if(device==NULL || (*device)->gdRefNum==0)return statusErr;
  1423.     if(!bugsPatched){
  1424.         PatchMacIIciVideoDriver();
  1425.         bugsPatched=1;
  1426.     }
  1427.  
  1428.     // Contrary to Apple's rules, these drivers crash if we attempt
  1429.     // a cscGetEntries call. So let's be polite and instead simply return
  1430.     // an error message indicating that this call is not available.
  1431.     name=GDName(device);
  1432.     version=GDVersion(device);
  1433.     if(EqualString(name,"\p.Display_Video_Apple_RBV1",1,1) && version==0)return statusErr;
  1434.     if(EqualString(name,"\p.Color_Video_Display",1,1) && version==9288)return statusErr;
  1435.     if(EqualString(name,"\p.Display_Video_Apple_DOMEMax",1,1) && version==2)return statusErr;
  1436.  
  1437.     vDSetEntryRecord.csStart=start;
  1438.     vDSetEntryRecord.csCount=count;
  1439.     vDSetEntryRecord.csTable=table;
  1440.     error=GDStatus((*device)->gdRefNum,cscGetEntries,(Ptr) &vDSetEntryRecord);
  1441.     return error;
  1442. }
  1443.  
  1444. OSErr GDGetPageCnt(GDHandle device,short mode,short *pagesPtr)
  1445. /*
  1446. Called "GetPages" in Designing Cards and Drivers, 3rd Ed. You tell it what mode
  1447. you're interested in. It tells you how many pages of video ram are available.
  1448. */
  1449. {
  1450.     VDPageInfo myVDPageInfo;
  1451.     int error;
  1452.  
  1453.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1454.     myVDPageInfo.csMode=mode;
  1455.     error=GDStatus((*device)->gdRefNum,cscGetPageCnt,(Ptr) &myVDPageInfo);
  1456.     if(!error)*pagesPtr=myVDPageInfo.csPage;
  1457.     return error;
  1458. }
  1459.  
  1460. OSErr GDGetPageBase(GDHandle device,short page,Ptr *baseAddrPtr)
  1461. /*
  1462. Called "GetBaseAddr" in Designing Cards and Drivers, 3rd Ed. You tell it what
  1463. page of video memory you're interested in (in the current video mode). It tells
  1464. you the base address of that page.
  1465. */
  1466. {
  1467.     VDPageInfo myVDPageInfo;
  1468.     int error;
  1469.  
  1470.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1471.     myVDPageInfo.csPage=page;
  1472.     error=GDStatus((*device)->gdRefNum,cscGetPageBase,(Ptr) &myVDPageInfo);
  1473.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1474.     return error;
  1475. }
  1476.  
  1477. OSErr GDGetGray(GDHandle device,Boolean *flagPtr)
  1478. // It tells you what the flag is set to. Do you want colors? (flag==0) Or do you
  1479. // want all colors mapped to luminance-equivalent gray tones? (flag==1).
  1480. {
  1481.     VDFlagRec myVDFlagRec;
  1482.     int error;
  1483.  
  1484.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1485.     error=GDStatus((*device)->gdRefNum,cscGetGray,(Ptr) &myVDFlagRec);
  1486.     *flagPtr=myVDFlagRec.flag;
  1487.     return error;
  1488. }
  1489.  
  1490. OSErr GDGetInterrupt(GDHandle device,Boolean *flagPtr)
  1491. // Get flag. 1 if VBL interrupts of this card are enabled. 0 if disabled. 
  1492. {
  1493.     VDFlagRec myVDFlagRec;
  1494.     int error;
  1495.  
  1496.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1497.     error=GDStatus((*device)->gdRefNum,cscGetInterrupt,(Ptr) &myVDFlagRec);
  1498.     *flagPtr=myVDFlagRec.flag;
  1499.     return error;
  1500. }
  1501.  
  1502. OSErr GDGetGamma(GDHandle device,GammaTbl **myGammaTblHandle)
  1503. /*
  1504. Returns a pointer to the Gamma table in the specified video device. (I.e. you
  1505. pass it a pointer to your pointer, a handle, which it uses to load your
  1506. pointer.)
  1507.  
  1508. Note that version 2 (in System ≤6.03) of the video driver for Apple's old video
  1509. card does not support this call due to a bug in the driver code. The later
  1510. versions of the driver (3, 4, and 5, in System 6.04 and later) work correctly.
  1511. */
  1512. {
  1513.     int error;
  1514.     VDGammaRecord myVDGammaRecord;
  1515.  
  1516.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1517.     myVDGammaRecord.csGTable=NULL;    // default address is NULL
  1518.     error=GDStatus((*device)->gdRefNum,cscGetGamma,(Ptr) &myVDGammaRecord);
  1519.     *myGammaTblHandle=(GammaTblPtr)myVDGammaRecord.csGTable;
  1520.     return error;
  1521. }
  1522.  
  1523. OSErr GDGetDefaultMode(GDHandle device,short *modePtr)
  1524. // It tells you what the default mode is. I'm not sure what this means.
  1525. {
  1526.     VDDefModeRec myVDDefModeRec;
  1527.     int error;
  1528.  
  1529.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1530.     error=GDStatus((*device)->gdRefNum,cscGetDefaultMode,(Ptr) &myVDDefModeRec);
  1531.     *modePtr=(unsigned char)myVDDefModeRec.spID;
  1532.     return error;
  1533. }
  1534.  
  1535. OSErr GDControl(int refNum,int csCode,Ptr csParamPtr)
  1536. // Uses low-level PBControl() call to implement a "Control()" call that works! 
  1537. // I don't know why this wasn't discussed in Apple Tech Note 262.
  1538. {
  1539.     CntrlParam control;
  1540.     int error;
  1541.     
  1542.     control.ioCompletion=NULL;
  1543.     control.ioCRefNum=refNum;
  1544.     control.csCode=csCode;
  1545.     *((Ptr *) &control.csParam[0]) = csParamPtr;
  1546.     error=PBControl((ParmBlkPtr) &control,0);
  1547.     return error;
  1548. }
  1549.  
  1550. OSErr GDStatus(int refNum,int csCode,Ptr csParamPtr)
  1551. // Uses low-level PBStatus() call to implement a "Status()" call that works! The
  1552. // need for this is explained in Apple Tech Note 262, which was issued in response
  1553. // to my bug report in summer of '89.
  1554. {
  1555.     CntrlParam control;
  1556.     int error;
  1557.     
  1558.     control.ioCompletion=NULL;
  1559.     control.ioCRefNum=refNum;
  1560.     control.csCode=csCode;
  1561.     *((Ptr *) &control.csParam[0]) = csParamPtr;
  1562.     error=PBStatus((ParmBlkPtr) &control,0);
  1563.     return error;
  1564. }
  1565.  
  1566. #if 0
  1567. /*
  1568. From: absurd@apple.apple.com (Tim Dierks, software saboteur)
  1569. Date: Fri, 20 Nov 1992 00:38:14 GMT
  1570. Organization: MacDTS Marauders
  1571.  
  1572. Here's the right way to get the slot number of a monitor, given its
  1573. GDevice:  (as a bonus, this also gets the name of the card in
  1574. question; to just get the slot, chop off all the lines after the
  1575. *slot = ... line.
  1576.  
  1577. 10/4/95 dgp added safety checks at beginning to make sure device handle is
  1578. not NULL and that the Slot Manager is present (e.g. a PCI machine).
  1579. */
  1580.  
  1581. OSErr GetSlotAndName(GDHandle device,short *slot,char *name)
  1582. {   OSErr error;
  1583.     SpBlock spBlock;
  1584.     Boolean slotMgrPresent;
  1585.     
  1586.     slot=-1;
  1587.     name[0]=0;
  1588.     if(TrapAvailable(_SlotManager))slotMgrPresent=(SVersion(&spBlock)==noErr);
  1589.     else slotMgrPresent=0;
  1590.     if(!slotMgrPresent || device==NULL || (*device)->gdRefNum==0)return -1;
  1591.     *slot = (**(AuxDCEHandle)GetDCtlEntry((**device).gdRefNum)).dCtlSlot;
  1592.     spBlock.spSlot = *slot;         // In the slot we're interested in
  1593.     spBlock.spID = 0;
  1594.     spBlock.spExtDev = 0;
  1595.     spBlock.spCategory = 1;         // Get the board sResource
  1596.     spBlock.spCType = 0;
  1597.     spBlock.spDrvrSW = 0;
  1598.     spBlock.spDrvrHW = 0;
  1599.     spBlock.spTBMask = 0;
  1600.     error = SNextTypeSRsrc(&spBlock);
  1601.     if(error)return error;
  1602.     spBlock.spID = 2;               // Getting the description string
  1603.                                     // spSPointer was set up by SNextTypesResource
  1604.     error = SGetCString(&spBlock);
  1605.     if(error)return error;
  1606.     strcpy(name,(char *)spBlock.spResult);  // Get the returned string
  1607.     DisposePtr((Ptr)spBlock.spResult);    // Undocumented; we have to dispose of it
  1608.     c2pstr(name);
  1609.     return noErr;
  1610. }
  1611. #endif
  1612.  
  1613. char *GDCardName(GDHandle device)
  1614. /*
  1615. Returns the address of a C string containing the name of the video card. You
  1616. should call DisposPtr() on the returned address when you no longer need it.
  1617. Takes about 1.5 ms; I don't know why Apple's slot routines are so slow. This
  1618. routine sets up the flags in the SNextTypeSRsrc() call quite differently from
  1619. the above example, but I don't know if that matters, since I've been using this
  1620. routine for a year or so without any problems.
  1621.  
  1622. Now works for PCI video devices as well.
  1623. */
  1624. {
  1625.     AuxDCE **auxDCEHandle;
  1626.     SpBlock spBlock,spBlock1;
  1627.     Boolean slotMgrPresent;
  1628.     char slotName[32],cardName[32],modelName[32];
  1629.     
  1630.     GetVideoProperties(device,slotName,cardName,modelName);    /* in Identify.c */
  1631.     if(strlen(cardName)>0){
  1632.         Ptr p;
  1633.         if(strlen(slotName)==0)strcpy(cardName,"Built-in video");
  1634.         p=NewPtr(strlen(cardName)+1);
  1635.         strcpy(p,cardName);
  1636.         return p;
  1637.     }
  1638.     if(TrapAvailable(_SlotManager))slotMgrPresent=(SVersion(&spBlock)==noErr);
  1639.     else slotMgrPresent=0;
  1640.     if(!slotMgrPresent || device==NULL || (*device)->gdRefNum==0){
  1641.         Ptr p;
  1642.         p=NewPtr(1);
  1643.         p[0]=0;
  1644.         return p;
  1645.     }
  1646.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1647.     spBlock.spSlot = (**auxDCEHandle).dCtlSlot;
  1648.     spBlock.spCategory = 0;
  1649.     spBlock.spCType =     0;
  1650.     spBlock.spDrvrSW =     0;
  1651.     spBlock.spDrvrHW =     1;
  1652.     spBlock.spTBMask = 0xf;
  1653.     spBlock.spID = 0;
  1654.     spBlock.spExtDev = 0;
  1655.     if(SNextTypeSRsrc(&spBlock) == noErr) {
  1656.         spBlock1.spsPointer = spBlock.spsPointer;
  1657.         spBlock1.spID = 2;
  1658.         SGetCString(&spBlock1);
  1659.         return (char *)spBlock1.spResult;
  1660.     }
  1661.     else{
  1662.         Ptr p;
  1663.         p=NewPtr(1);
  1664.         p[0]=0;
  1665.         return p;
  1666.     }
  1667. }
  1668.  
  1669. #if 0
  1670.     flags The flags word in the driver’s DCE.
  1671.     
  1672.     
  1673.     //#include <NameRegistry.h>
  1674.     //#include <Drivers.h>
  1675. #endif
  1676.  
  1677. OSErr GDGestalt(GDHandle device,OSType driverGestaltSelector,unsigned long *driverGestaltResponsePtr)
  1678. {
  1679.     int error;
  1680.  
  1681.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1682.     error=DriverGestalt((*device)->gdRefNum,driverGestaltSelector,driverGestaltResponsePtr);
  1683.     return error;
  1684. }
  1685.  
  1686. struct DriverGestaltParam {
  1687.     QElemPtr qLink;
  1688.     short qType;
  1689.     short ioTrap;
  1690.     Ptr ioCmdAddr;
  1691.     ProcPtr ioCompletion;
  1692.     OSErr ioResult;
  1693.     StringPtr ioNamePtr;
  1694.     short ioVRefNum;
  1695.     short ioCRefNum; /* refNum for I/O operation*/
  1696.     short csCode; /* == driverGestaltCode */
  1697.     OSType driverGestaltSelector;
  1698.     unsigned long driverGestaltResponse;
  1699. };
  1700. typedef struct DriverGestaltParam DriverGestaltParam;
  1701. enum{kcsDriverGestalt=43};
  1702. enum{kmDriverGestaltEnableMask=1L<<2};
  1703.  
  1704. Boolean GDGestaltIsOn(GDHandle device)
  1705. {
  1706.     AuxDCE **auxDCEHandle;
  1707.  
  1708.     if(device==NULL || (*device)->gdRefNum==0) return 0;
  1709.     auxDCEHandle=(AuxDCE **)GetDCtlEntry((*device)->gdRefNum);
  1710.     return (**auxDCEHandle).dCtlFlags & kmDriverGestaltEnableMask;
  1711. }
  1712.  
  1713. OSErr DriverGestalt(int refNum,OSType driverGestaltSelector,unsigned long *driverGestaltResponsePtr)
  1714. /*
  1715. Implements Driver Gestalt, documented in Designing PCI Cards and Drivers
  1716. */
  1717. {
  1718.     DriverGestaltParam param;
  1719.     int error;
  1720.     AuxDCE **auxDCEHandle;
  1721.  
  1722.     auxDCEHandle=(AuxDCE **)GetDCtlEntry(refNum);
  1723.     if(!((**auxDCEHandle).dCtlFlags & kmDriverGestaltEnableMask))return statusErr;
  1724.     param.ioCompletion=NULL;
  1725.     param.ioCRefNum=refNum;
  1726.     param.csCode=kcsDriverGestalt;
  1727.     param.driverGestaltSelector=driverGestaltSelector;
  1728.     param.driverGestaltResponse=0;
  1729.     error=PBStatus((ParmBlkPtr) ¶m,0);
  1730.     if(driverGestaltResponsePtr!=NULL) *driverGestaltResponsePtr=param.driverGestaltResponse;
  1731.     return error;
  1732. }
  1733.  
  1734. #if 0
  1735.     struct DriverType {
  1736.         Str31 nameInfoStr;
  1737.         NumVersion version;
  1738.     }
  1739.     typedef UInt32 DeviceTypeMember;
  1740.     typedef struct DriverType DriverType;
  1741.     typedef struct DriverType *DriverTypePtr;
  1742.     struct DriverOSRuntime {
  1743.     RuntimeOptions driverRuntime;
  1744.     Str31 driverName;
  1745.     UInt32 driverDescReserved[8];
  1746.     };
  1747.     typedef OptionBits RuntimeOptions;
  1748.     typedef struct DriverOSRuntime DriverOSRuntime;
  1749.     
  1750.     struct DriverDescription {
  1751.         OSType driverDescSignature;
  1752.         DriverDescVersion driverDescVersion;
  1753.         DriverType driverType;
  1754.         DriverOSRuntime driverOSRuntimeInfo;
  1755.         DriverOSService driverServices;
  1756.     };
  1757.     typedef struct DriverDescription DriverDescription;
  1758.     typedef struct DriverDescription *DriverDescriptionPtr;
  1759.  
  1760.     OSErr GetDriverName(GDHandle device,unsigned char *name);
  1761.     
  1762.     OSErr GetDriverName(GDHandle device,unsigned char *name)
  1763.     {
  1764.         long nameRegistryVersion;
  1765.         OSErr error;
  1766.         UnitNumber unit;
  1767.         DriverFlags flags;
  1768.         FSSpec driverFileSpec;
  1769.         RegEntryID regEntryID;
  1770.         CFragHFSLocator loc;
  1771.         CFragConnectionID fragmentConnID;
  1772.         DriverOpenCount openCount;
  1773.         DriverEntryPointPtr fragmentMain;
  1774.         DriverDescription driverDescription;
  1775.     
  1776.         name[0]=0;
  1777.         error=Gestalt('nreg',&nameRegistryVersion);
  1778.         if(!error){
  1779.             loc.u.onDisk.fileSpec = &driverFileSpec;
  1780.             error=GetDriverInformation((*device)->gdRefNum,&unit,&flags,&openCount,name
  1781.                 ,®EntryID,&loc,&fragmentConnID,&fragmentMain,&driverDescription);
  1782.         }
  1783.         return error;
  1784.     }
  1785. #endif
  1786.  
  1787. unsigned char *GDName(GDHandle device)
  1788. // Returns a pointer to the name of the driver (a pascal string). 
  1789. {
  1790.     VideoDriver *videoDriverPtr;
  1791.  
  1792.     if(device==NULL || (*device)->gdRefNum==0)return "\p";
  1793.     videoDriverPtr=GDDriverAddress(device);
  1794.     return videoDriverPtr->name;
  1795. }
  1796.  
  1797. char *GDNameStr(GDHandle device)
  1798. // Returns the driver name as a C string.
  1799. {
  1800.     unsigned char *sp;
  1801.     static char name[32];
  1802.     
  1803.     sp=GDName(device);
  1804.     memcpy(name,sp,sp[0]+1);
  1805.     return p2cstr((unsigned char *)name);
  1806. }
  1807.  
  1808. int GDVersion(GDHandle device)
  1809. // Returns the version number of the driver. From the first word-aligned word after
  1810. // the name string.
  1811. {
  1812.     int version;
  1813.     unsigned char *bytePtr;
  1814.  
  1815.     if(device==NULL || (*device)->gdRefNum==0)return 0;
  1816.     bytePtr=GDName(device);
  1817.     bytePtr += 1+bytePtr[0];    /* go to end of Pascal string */
  1818.     bytePtr = (unsigned char *)((long)(bytePtr+1) & ~1);    // round up to word boundary
  1819.     version = *(short *)bytePtr;
  1820.     return version;
  1821. }
  1822.  
  1823. VideoDriver *GDDriverAddress(GDHandle device)
  1824. // Returns a pointer to the driver, whether in ROM or RAM. 
  1825. {
  1826.     AuxDCE **auxDCEHandle;
  1827.     VideoDriver *videoDriverPtr;
  1828.  
  1829.     if(device==NULL || (*device)->gdRefNum==0)return NULL;
  1830.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1831.     if((**auxDCEHandle).dCtlFlags & dRAMBasedMask){
  1832.         /* RAM-based driver. */
  1833.         videoDriverPtr=*(VideoDriver **) (**auxDCEHandle).dCtlDriver;
  1834.     }
  1835.     else{
  1836.         /* ROM-based driver. */
  1837.         videoDriverPtr=(VideoDriver *) (**auxDCEHandle).dCtlDriver;
  1838.     }
  1839.     return videoDriverPtr;
  1840. }
  1841.  
  1842. /*
  1843. ROUTINE: PatchMacIIciVideoDriver
  1844. PURPOSE:
  1845. It is unlikely that you will need to call this explicitly, because it is called
  1846. automatically by GDGetEntries the first time it is invoked, and the sole purpose
  1847. of this routine is to fix a driver bug that would cause a crash when called by
  1848. GDGetEntries.
  1849.  
  1850. The Mac IIci built-in video driver (.Display_Video_Apple_RBV1 driver, version 0)
  1851. has a bug that causes it to crash if you try to do a cscGetEntries Status request.
  1852. PatchMacIIciVideoDriver() will find and patch the memory-resident copy of the
  1853. buggy driver. Only two instructions are modified, to save and restore more
  1854. registers. This fix persists only until the next reboot. If the patch is
  1855. successfully applied the version number is increased from 0 to 100, to
  1856. distinguish it from versions 0 and 1.
  1857.  
  1858. A returned value of 1 indicates success: the needed patch was applied, either now
  1859. or previously. A return value of 0 indicates no patch was needed.
  1860.  
  1861. This patch is based on a comparison of the version 0 and 1 drivers used by the
  1862. Mac IIci and IIsi, respectively. The patch changes a pair of save and restore
  1863. operations (MOVEM.L to and from the stack) to save and restore registers D1 and
  1864. A1 as well as D4, A3, and A4. There are many other differences between versions
  1865. 0 and 1 of the driver, but this change is enough to keep the version 0 driver
  1866. from crashing when we attempt to read the clut by calling GDGetEntries.
  1867.  
  1868. The only change that the Mac operating system could possibly notice is that,
  1869. when we're done patching, we set the handle to be non-purgeable, since purging
  1870. and reloading the driver would eliminate the patch.
  1871.  
  1872. edward_de_Jong@bmug.org and Robert Savoy (SAVOY@RISVAX.ROWLAND.ORG) reported
  1873. that their Mac IIci computers' built-in video driver is ROM-based, so
  1874. PatchMacIIciVideoDriver was enhanced to deal with a ROM-based driver, by copying
  1875. the driver into RAM, making that the active driver, and patching it. Robert
  1876. Savoy reports that it works fine.
  1877.  
  1878. An alternative, permanent, solution is described in the file "Video synch":
  1879. upgrading to Apple's bug-free version 1 of the driver. However, that solution
  1880. only works if the Mac IIci has more than one monitor.
  1881.  
  1882. */
  1883.  
  1884. int PatchMacIIciVideoDriver(void)
  1885. {
  1886.     GDHandle device;
  1887.     short *w;
  1888.     AuxDCE **auxDCEHandle;
  1889.     Handle handle;
  1890.     enum{badVersion=0};
  1891.     int error;
  1892.     long value;
  1893.     
  1894.     error=Gestalt(gestaltQuickdrawVersion,&value);
  1895.     if(error || value<gestalt8BitQD)return 0;    // need 8-bit quickdraw
  1896.     device = GetDeviceList();
  1897.     while(1) {
  1898.         if(device==NULL || (*device)->gdRefNum==0)return 0;
  1899.         if (!TestDeviceAttribute(device,screenDevice)
  1900.             || !TestDeviceAttribute(device,screenActive)){
  1901.             device=GetNextDevice(device);
  1902.             continue;
  1903.         }
  1904.         if(EqualString("\p.Display_Video_Apple_RBV1",GDName(device),1,1))
  1905.             switch(GDVersion(device)){
  1906.                 case badVersion:
  1907.                     break;
  1908.                 case badVersion+100:    // already patched
  1909.                     return 1;
  1910.                 default:
  1911.                     return 0;
  1912.         }else{
  1913.             device=GetNextDevice(device);
  1914.             continue;
  1915.         }
  1916.         break;
  1917.     }
  1918.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1919.     
  1920.     // Move ROM-based driver into RAM.
  1921.     if(!((**auxDCEHandle).dCtlFlags & dRAMBasedMask)){
  1922.         long bytes;
  1923.         VideoDriver *driver;
  1924.         
  1925.         driver=(VideoDriver *)(**auxDCEHandle).dCtlDriver;
  1926.         // Sometimes the word preceding the driver in ROM seems to be the
  1927.         // driver size, but not always, e.g. the built-in driver on the Mac IIsi.
  1928.         bytes=*((short *)driver-1);
  1929.         // Driver size unknown, guessing (generously) at twice the highest offset.
  1930.         bytes=driver->open;
  1931.         if(bytes<driver->prime)bytes=driver->prime;
  1932.         if(bytes<driver->control)bytes=driver->control;
  1933.         if(bytes<driver->status)bytes=driver->status;
  1934.         if(bytes<driver->close)bytes=driver->close;
  1935.         bytes*=2;
  1936.         // We know the Mac IIci driver size to be 1896
  1937.         // when ROM version is 124 rev. 1, but who knows for later ROMs?
  1938.         //bytes=1896;
  1939.         handle=NewHandleSys(bytes);
  1940.         if(handle==NULL)return 0;    // Insufficient room on System heap.
  1941.         HLockHi(handle);
  1942.         BlockMove((Ptr)driver,*handle,bytes);
  1943.         (**auxDCEHandle).dCtlDriver=(Ptr)handle;
  1944.         (**auxDCEHandle).dCtlFlags |= dRAMBasedMask;        
  1945.     }
  1946.     
  1947.     // Patch RAM-based driver.
  1948.     handle=(Handle)(**auxDCEHandle).dCtlDriver;
  1949.     w=*(short **)handle;
  1950.     if(w[0x51e/2]!=0x818 || w[0x590/2]!=0x1810 || w[0x2c/2]!=badVersion){
  1951.         printf("PatchMacIIciVideoDriver error.\n");
  1952.         return 0;
  1953.     }
  1954.     w[0x51e/2]=0x4858;
  1955.     w[0x590/2]=0x1a12;
  1956.     w[0x2c/2]+=100;                                    // Change version number.
  1957.     if(w[0x51e/2]!=0x4858 || w[0x590/2]!=0x1a12){
  1958.         printf("PatchMacIIciVideoDriver error.\n");
  1959.         return 0;
  1960.     }
  1961.     HNoPurge(handle);
  1962.     return 1;
  1963. }
  1964.  
  1965. /*
  1966. Received:    10/24
  1967. From:        Fernando Urbina, nano@apple.com
  1968. To:          Denis Pelli, denis@cns.nyu.edu
  1969.  
  1970. The following is the information on the private call for the 7500 and the 
  1971. 8500 to disable waiting for VBL's and to change the time that we wait for 
  1972. the CLUT to settle after writing each entry in the CLUT.  As shipped, the 
  1973. driver waits for 800 nanoseconds after writing each RGB triplet, to allow 
  1974. the hardware to increment the CLUT address.
  1975.  
  1976. cscSetTimeDelays is used to set some flags and time delays used to write the
  1977. CLUT. Use PBControl to issue the call, with the csParam[0] containing a pointer
  1978. to a VDTimeDelay structure. Set the "validMask" field with the bits
  1979. indicating which parameters you want to set.
  1980.  
  1981. cscGetTimeDelays is used to examine the current values of the flags and time
  1982. delays. Use PBStatus instead of PBControl. Set the "validMask" field
  1983. with the bits indicating which parameters you want to get.
  1984.  
  1985. The following is the definition of the fields of the VDTimeDelay struct:
  1986.  
  1987. flags, bit 0:  DontWaitForVBL flag:  When false, it means that the driver should
  1988. wait for a VBL before writing the CLUT.  When true, the driver should NOT wait
  1989. for a VBL.
  1990.  
  1991. flags, bit 1:  SetCLUTAddrRegTiming flag:  When false, use the default timing.
  1992. When true, use paramOne and paramTwo to specify the delay in nanoseconds.
  1993.  
  1994. validMask: Specifies which bits in flags are valid.  Bits are valid when
  1995. corresponding bit position is 1.
  1996.  
  1997. paramOne,paramTwo: When the SetCLUTAddrRegTiming bit of the validMask is set,
  1998. then these fields specify the delay, in nanoseconds: nanoseconds.hi in paramOne
  1999. and nanoseconds.lo in paramTwo.  See Designing PCI Cards & Drivers for the
  2000. Nanoseconds data structure.
  2001.  
  2002. */
  2003. enum{cscSetTimeDelays = 141};    // Used to set the different time delays
  2004. enum{cscGetTimeDelays = 141};
  2005. enum{gDontWaitForVBLMask=1,gSetCLUTTimingMask=2};
  2006. #if PRAGMA_ALIGN_SUPPORTED || __MWERKS__
  2007.     #pragma options align=mac68k
  2008. #endif
  2009. struct VDTimeDelays{
  2010.     UInt32 flags;
  2011.     UInt32 validMask;
  2012.     UInt32 paramOne;
  2013.     UInt32 paramTwo;
  2014. };
  2015. typedef struct VDTimeDelays VDTimeDelays;
  2016. #if PRAGMA_ALIGN_SUPPORTED || __MWERKS__
  2017.     #pragma options align=reset
  2018. #endif
  2019. OSErr GDSetTimeDelays(GDHandle device,VDTimeDelays *timeDelaysPtr);
  2020. OSErr GDGetTimeDelays(GDHandle device,VDTimeDelays *timeDelaysPtr);
  2021.  
  2022. OSErr GDSetDelay(GDHandle device,Boolean dontWaitForVBL,double nanoseconds)
  2023. {
  2024.     OSErr error;
  2025.     VDTimeDelays timeDelays={0,0,0,0};
  2026.     
  2027.     timeDelays.validMask=gDontWaitForVBLMask;
  2028.     if(dontWaitForVBL)timeDelays.flags=gDontWaitForVBLMask;
  2029.     else timeDelays.flags=0;
  2030.     if(IsFinite(nanoseconds)){
  2031.         timeDelays.flags|=gSetCLUTTimingMask;
  2032.         timeDelays.validMask|=gSetCLUTTimingMask;
  2033.         timeDelays.paramOne=nanoseconds/0x10000/0x10000;
  2034.         timeDelays.paramTwo=nanoseconds-(double)timeDelays.paramOne*0x10000*0x10000;
  2035.     }else timeDelays.paramOne=timeDelays.paramTwo=0; 
  2036.     error=GDSetTimeDelays(device,&timeDelays);
  2037.     return error;
  2038. }
  2039. OSErr GDGetDelay(GDHandle device,Boolean *dontWaitForVBLPtr,double *nanosecondsPtr)
  2040. {
  2041.     OSErr error;
  2042.     VDTimeDelays timeDelays={0,0,0,0};
  2043.     
  2044.     timeDelays.validMask=gDontWaitForVBLMask|gSetCLUTTimingMask;
  2045.     error=GDGetTimeDelays(device,&timeDelays);
  2046.     if(error)return error;
  2047.     if(dontWaitForVBLPtr!=NULL){
  2048.         if(timeDelays.flags&gDontWaitForVBLMask) *dontWaitForVBLPtr=1;
  2049.         else *dontWaitForVBLPtr=0;
  2050.     }
  2051.     if(nanosecondsPtr!=NULL)
  2052.         *nanosecondsPtr=(double)timeDelays.paramTwo+(double)timeDelays.paramOne*0x10000*0x10000;
  2053.     return error;
  2054. }
  2055. OSErr GDSetTimeDelays(GDHandle device,VDTimeDelays *timeDelaysPtr)
  2056. {
  2057.     OSErr error;
  2058.     long stackSpace;
  2059.     
  2060.     stackSpace=StackSpace();
  2061.     if(device==NULL || (*device)->gdRefNum==0 || timeDelaysPtr==NULL) return controlErr;
  2062.     error=GDControl((*device)->gdRefNum,cscSetTimeDelays,(Ptr)timeDelaysPtr);
  2063.     stackSpace=StackSpace();
  2064.     return error;
  2065. }
  2066. OSErr GDGetTimeDelays(GDHandle device,VDTimeDelays *timeDelaysPtr)
  2067. {
  2068.     OSErr error;
  2069.     long stackSpace;
  2070.     
  2071.     stackSpace=StackSpace();
  2072.     if(device==NULL || (*device)->gdRefNum==0 || timeDelaysPtr==NULL) return statusErr;
  2073.     error=GDStatus((*device)->gdRefNum,cscGetTimeDelays,(Ptr)timeDelaysPtr);
  2074.     stackSpace=StackSpace();
  2075.     return error;
  2076. }
  2077. Boolean IsPCIMac(void)
  2078. {
  2079.     static Boolean pci,firstTime=1;
  2080.  
  2081.         if(firstTime){
  2082.             long templong;
  2083.             int error;
  2084.             #define gestaltNameRegistryVersion 'nreg'    // support for old versions of Gestalt.h
  2085.             error=Gestalt(gestaltNameRegistryVersion,&templong);
  2086.             pci=(error==0);    // are there PCI slots?
  2087.             firstTime=0;
  2088.         }
  2089.         return pci;
  2090. }
  2091. void GDRestoreBlackAndWhite(GDHandle device)
  2092. // Restore the first & last clut entries to white and black.
  2093. {
  2094.     short clutSize;
  2095.     int error;
  2096.     ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  2097.  
  2098.     clutSize=GDClutSize(device);
  2099.     switch((**device).gdType){
  2100.     case clutType:
  2101.         error=GDSetEntries(device,0,0,&white);
  2102.         error=GDSetEntries(device,clutSize-1,0,&black);    // Fixed 3/4/96
  2103.         break;
  2104.     case directType:
  2105.         error=GDDirectSetEntries(device,0,0,&black);
  2106.         error=GDDirectSetEntries(device,clutSize-1,0,&white); // Fixed 3/4/96
  2107.         break;
  2108.     default:
  2109.         break;
  2110.     }
  2111. }
  2112.